move token generation to admin and add needed security to it

This commit is contained in:
Cam Otts 2023-01-10 09:53:41 -06:00
parent 354ccb853f
commit bb3d488212
No known key found for this signature in database
GPG Key ID: 367B7C7EBD84A8BD
17 changed files with 239 additions and 161 deletions

View File

@ -4,7 +4,7 @@ import (
"fmt"
"github.com/jaevor/go-nanoid"
"github.com/openziti-test-kitchen/zrok/rest_client_zrok/invite"
"github.com/openziti-test-kitchen/zrok/rest_client_zrok/admin"
"github.com/openziti-test-kitchen/zrok/rest_model_zrok"
"github.com/openziti-test-kitchen/zrok/zrokdir"
"github.com/spf13/cobra"
@ -49,11 +49,11 @@ func (cmd *generateCommand) run(_ *cobra.Command, args []string) {
}
panic(err)
}
req := invite.NewInviteGenerateParams()
req := admin.NewInviteGenerateParams()
req.Body = &rest_model_zrok.InviteGenerateRequest{
Tokens: tokens,
}
_, err = zrok.Invite.InviteGenerate(req)
_, err = zrok.Admin.InviteGenerate(req, mustGetAdminAuth())
if err != nil {
if !panicInstead {
showError("error creating invite tokens", err)

View File

@ -33,11 +33,11 @@ func Run(inCfg *Config) error {
api.AdminCreateFrontendHandler = newCreateFrontendHandler()
api.AdminCreateIdentityHandler = newCreateIdentityHandler()
api.AdminDeleteFrontendHandler = newDeleteFrontendHandler()
api.AdminInviteGenerateHandler = newInviteGenerateHandler()
api.AdminListFrontendsHandler = newListFrontendsHandler()
api.AdminUpdateFrontendHandler = newUpdateFrontendHandler()
api.EnvironmentEnableHandler = newEnableHandler()
api.EnvironmentDisableHandler = newDisableHandler()
api.InviteInviteGenerateHandler = newInviteGenerateHandler()
api.MetadataGetEnvironmentDetailHandler = newEnvironmentDetailHandler()
api.MetadataGetShareDetailHandler = newShareDetailHandler()
api.MetadataOverviewHandler = metadata.OverviewHandlerFunc(overviewHandler)

View File

@ -3,8 +3,9 @@ package controller
import (
"github.com/go-openapi/runtime/middleware"
"github.com/openziti-test-kitchen/zrok/controller/store"
"github.com/openziti-test-kitchen/zrok/rest_model_zrok"
"github.com/openziti-test-kitchen/zrok/rest_server_zrok/operations/account"
"github.com/openziti-test-kitchen/zrok/rest_server_zrok/operations/invite"
"github.com/openziti-test-kitchen/zrok/rest_server_zrok/operations/admin"
"github.com/openziti-test-kitchen/zrok/util"
"github.com/sirupsen/logrus"
)
@ -108,10 +109,15 @@ func newInviteGenerateHandler() *inviteGenerateHandler {
return &inviteGenerateHandler{}
}
func (handler *inviteGenerateHandler) Handle(params invite.InviteGenerateParams) middleware.Responder {
func (handler *inviteGenerateHandler) Handle(params admin.InviteGenerateParams, principal *rest_model_zrok.Principal) middleware.Responder {
if !principal.Admin {
logrus.Errorf("invalid admin principal")
return admin.NewListFrontendsUnauthorized()
}
if params.Body == nil || len(params.Body.Tokens) == 0 {
logrus.Error("missing tokens")
return invite.NewInviteGenerateBadRequest()
return admin.NewInviteGenerateBadRequest()
}
logrus.Infof("received invite generate request with %d tokens", len(params.Body.Tokens))
@ -124,13 +130,13 @@ func (handler *inviteGenerateHandler) Handle(params invite.InviteGenerateParams)
tx, err := str.Begin()
if err != nil {
logrus.Error(err)
return invite.NewInviteGenerateInternalServerError()
return admin.NewInviteGenerateInternalServerError()
}
defer func() { _ = tx.Rollback() }()
if err := str.CreateInvites(invites, tx); err != nil {
logrus.Error(err)
return invite.NewInviteGenerateInternalServerError()
return admin.NewInviteGenerateInternalServerError()
}
if err := tx.Commit(); err != nil {
@ -138,5 +144,5 @@ func (handler *inviteGenerateHandler) Handle(params invite.InviteGenerateParams)
return account.NewInviteInternalServerError()
}
return invite.NewInviteGenerateCreated()
return admin.NewInviteGenerateCreated()
}

View File

@ -36,6 +36,8 @@ type ClientService interface {
DeleteFrontend(params *DeleteFrontendParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteFrontendOK, error)
InviteGenerate(params *InviteGenerateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*InviteGenerateCreated, error)
ListFrontends(params *ListFrontendsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListFrontendsOK, error)
UpdateFrontend(params *UpdateFrontendParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateFrontendOK, error)
@ -160,6 +162,45 @@ func (a *Client) DeleteFrontend(params *DeleteFrontendParams, authInfo runtime.C
panic(msg)
}
/*
InviteGenerate invite generate API
*/
func (a *Client) InviteGenerate(params *InviteGenerateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*InviteGenerateCreated, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewInviteGenerateParams()
}
op := &runtime.ClientOperation{
ID: "inviteGenerate",
Method: "POST",
PathPattern: "/invite/generate",
ProducesMediaTypes: []string{"application/zrok.v1+json"},
ConsumesMediaTypes: []string{"application/zrok.v1+json"},
Schemes: []string{"http"},
Params: params,
Reader: &InviteGenerateReader{formats: a.formats},
AuthInfo: authInfo,
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*InviteGenerateCreated)
if ok {
return success, nil
}
// unexpected success response
// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
msg := fmt.Sprintf("unexpected success response for inviteGenerate: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
/*
ListFrontends list frontends API
*/

View File

@ -1,6 +1,6 @@
// Code generated by go-swagger; DO NOT EDIT.
package invite
package admin
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

View File

@ -1,6 +1,6 @@
// Code generated by go-swagger; DO NOT EDIT.
package invite
package admin
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
@ -32,6 +32,12 @@ func (o *InviteGenerateReader) ReadResponse(response runtime.ClientResponse, con
return nil, err
}
return nil, result
case 401:
result := NewInviteGenerateUnauthorized()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
case 500:
result := NewInviteGenerateInternalServerError()
if err := result.readResponse(response, consumer, o.formats); err != nil {
@ -145,6 +151,57 @@ func (o *InviteGenerateBadRequest) readResponse(response runtime.ClientResponse,
return nil
}
// NewInviteGenerateUnauthorized creates a InviteGenerateUnauthorized with default headers values
func NewInviteGenerateUnauthorized() *InviteGenerateUnauthorized {
return &InviteGenerateUnauthorized{}
}
/*
InviteGenerateUnauthorized describes a response with status code 401, with default header values.
unauthorized
*/
type InviteGenerateUnauthorized struct {
}
// IsSuccess returns true when this invite generate unauthorized response has a 2xx status code
func (o *InviteGenerateUnauthorized) IsSuccess() bool {
return false
}
// IsRedirect returns true when this invite generate unauthorized response has a 3xx status code
func (o *InviteGenerateUnauthorized) IsRedirect() bool {
return false
}
// IsClientError returns true when this invite generate unauthorized response has a 4xx status code
func (o *InviteGenerateUnauthorized) IsClientError() bool {
return true
}
// IsServerError returns true when this invite generate unauthorized response has a 5xx status code
func (o *InviteGenerateUnauthorized) IsServerError() bool {
return false
}
// IsCode returns true when this invite generate unauthorized response a status code equal to that given
func (o *InviteGenerateUnauthorized) IsCode(code int) bool {
return code == 401
}
func (o *InviteGenerateUnauthorized) Error() string {
return fmt.Sprintf("[POST /invite/generate][%d] inviteGenerateUnauthorized ", 401)
}
func (o *InviteGenerateUnauthorized) String() string {
return fmt.Sprintf("[POST /invite/generate][%d] inviteGenerateUnauthorized ", 401)
}
func (o *InviteGenerateUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}
// NewInviteGenerateInternalServerError creates a InviteGenerateInternalServerError with default headers values
func NewInviteGenerateInternalServerError() *InviteGenerateInternalServerError {
return &InviteGenerateInternalServerError{}

View File

@ -1,79 +0,0 @@
// Code generated by go-swagger; DO NOT EDIT.
package invite
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
)
// New creates a new invite API client.
func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService {
return &Client{transport: transport, formats: formats}
}
/*
Client for invite API
*/
type Client struct {
transport runtime.ClientTransport
formats strfmt.Registry
}
// ClientOption is the option for Client methods
type ClientOption func(*runtime.ClientOperation)
// ClientService is the interface for Client methods
type ClientService interface {
InviteGenerate(params *InviteGenerateParams, opts ...ClientOption) (*InviteGenerateCreated, error)
SetTransport(transport runtime.ClientTransport)
}
/*
InviteGenerate invite generate API
*/
func (a *Client) InviteGenerate(params *InviteGenerateParams, opts ...ClientOption) (*InviteGenerateCreated, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewInviteGenerateParams()
}
op := &runtime.ClientOperation{
ID: "inviteGenerate",
Method: "POST",
PathPattern: "/invite/generate",
ProducesMediaTypes: []string{"application/zrok.v1+json"},
ConsumesMediaTypes: []string{"application/zrok.v1+json"},
Schemes: []string{"http"},
Params: params,
Reader: &InviteGenerateReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*InviteGenerateCreated)
if ok {
return success, nil
}
// unexpected success response
// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
msg := fmt.Sprintf("unexpected success response for inviteGenerate: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
// SetTransport changes the transport on the client
func (a *Client) SetTransport(transport runtime.ClientTransport) {
a.transport = transport
}

View File

@ -13,7 +13,6 @@ import (
"github.com/openziti-test-kitchen/zrok/rest_client_zrok/account"
"github.com/openziti-test-kitchen/zrok/rest_client_zrok/admin"
"github.com/openziti-test-kitchen/zrok/rest_client_zrok/environment"
"github.com/openziti-test-kitchen/zrok/rest_client_zrok/invite"
"github.com/openziti-test-kitchen/zrok/rest_client_zrok/metadata"
"github.com/openziti-test-kitchen/zrok/rest_client_zrok/share"
)
@ -63,7 +62,6 @@ func New(transport runtime.ClientTransport, formats strfmt.Registry) *Zrok {
cli.Account = account.New(transport, formats)
cli.Admin = admin.New(transport, formats)
cli.Environment = environment.New(transport, formats)
cli.Invite = invite.New(transport, formats)
cli.Metadata = metadata.New(transport, formats)
cli.Share = share.New(transport, formats)
return cli
@ -116,8 +114,6 @@ type Zrok struct {
Environment environment.ClientService
Invite invite.ClientService
Metadata metadata.ClientService
Share share.ClientService
@ -131,7 +127,6 @@ func (c *Zrok) SetTransport(transport runtime.ClientTransport) {
c.Account.SetTransport(transport)
c.Admin.SetTransport(transport)
c.Environment.SetTransport(transport)
c.Invite.SetTransport(transport)
c.Metadata.SetTransport(transport)
c.Share.SetTransport(transport)
}

View File

@ -433,8 +433,13 @@ func init() {
},
"/invite/generate": {
"post": {
"security": [
{
"key": []
}
],
"tags": [
"invite"
"admin"
],
"operationId": "inviteGenerate",
"parameters": [
@ -453,6 +458,9 @@ func init() {
"400": {
"description": "invitation tokens not created"
},
"401": {
"description": "unauthorized"
},
"500": {
"description": "internal server error"
}
@ -1593,8 +1601,13 @@ func init() {
},
"/invite/generate": {
"post": {
"security": [
{
"key": []
}
],
"tags": [
"invite"
"admin"
],
"operationId": "inviteGenerate",
"parameters": [
@ -1613,6 +1626,9 @@ func init() {
"400": {
"description": "invitation tokens not created"
},
"401": {
"description": "unauthorized"
},
"500": {
"description": "internal server error"
}

View File

@ -1,6 +1,6 @@
// Code generated by go-swagger; DO NOT EDIT.
package invite
package admin
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
@ -9,19 +9,21 @@ import (
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/openziti-test-kitchen/zrok/rest_model_zrok"
)
// InviteGenerateHandlerFunc turns a function with the right signature into a invite generate handler
type InviteGenerateHandlerFunc func(InviteGenerateParams) middleware.Responder
type InviteGenerateHandlerFunc func(InviteGenerateParams, *rest_model_zrok.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn InviteGenerateHandlerFunc) Handle(params InviteGenerateParams) middleware.Responder {
return fn(params)
func (fn InviteGenerateHandlerFunc) Handle(params InviteGenerateParams, principal *rest_model_zrok.Principal) middleware.Responder {
return fn(params, principal)
}
// InviteGenerateHandler interface for that can handle valid invite generate params
type InviteGenerateHandler interface {
Handle(InviteGenerateParams) middleware.Responder
Handle(InviteGenerateParams, *rest_model_zrok.Principal) middleware.Responder
}
// NewInviteGenerate creates a new http.Handler for the invite generate operation
@ -30,7 +32,7 @@ func NewInviteGenerate(ctx *middleware.Context, handler InviteGenerateHandler) *
}
/*
InviteGenerate swagger:route POST /invite/generate invite inviteGenerate
InviteGenerate swagger:route POST /invite/generate admin inviteGenerate
InviteGenerate invite generate API
*/
@ -45,12 +47,25 @@ func (o *InviteGenerate) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
*r = *rCtx
}
var Params = NewInviteGenerateParams()
uprinc, aCtx, err := o.Context.Authorize(r, route)
if err != nil {
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
if aCtx != nil {
*r = *aCtx
}
var principal *rest_model_zrok.Principal
if uprinc != nil {
principal = uprinc.(*rest_model_zrok.Principal) // this is really a rest_model_zrok.Principal, I promise
}
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params) // actually handle the request
res := o.Handler.Handle(Params, principal) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@ -1,6 +1,6 @@
// Code generated by go-swagger; DO NOT EDIT.
package invite
package admin
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

View File

@ -1,6 +1,6 @@
// Code generated by go-swagger; DO NOT EDIT.
package invite
package admin
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
@ -61,6 +61,31 @@ func (o *InviteGenerateBadRequest) WriteResponse(rw http.ResponseWriter, produce
rw.WriteHeader(400)
}
// InviteGenerateUnauthorizedCode is the HTTP code returned for type InviteGenerateUnauthorized
const InviteGenerateUnauthorizedCode int = 401
/*
InviteGenerateUnauthorized unauthorized
swagger:response inviteGenerateUnauthorized
*/
type InviteGenerateUnauthorized struct {
}
// NewInviteGenerateUnauthorized creates InviteGenerateUnauthorized with default headers values
func NewInviteGenerateUnauthorized() *InviteGenerateUnauthorized {
return &InviteGenerateUnauthorized{}
}
// WriteResponse to the client
func (o *InviteGenerateUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses
rw.WriteHeader(401)
}
// InviteGenerateInternalServerErrorCode is the HTTP code returned for type InviteGenerateInternalServerError
const InviteGenerateInternalServerErrorCode int = 500

View File

@ -1,6 +1,6 @@
// Code generated by go-swagger; DO NOT EDIT.
package invite
package admin
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command

View File

@ -23,7 +23,6 @@ import (
"github.com/openziti-test-kitchen/zrok/rest_server_zrok/operations/account"
"github.com/openziti-test-kitchen/zrok/rest_server_zrok/operations/admin"
"github.com/openziti-test-kitchen/zrok/rest_server_zrok/operations/environment"
"github.com/openziti-test-kitchen/zrok/rest_server_zrok/operations/invite"
"github.com/openziti-test-kitchen/zrok/rest_server_zrok/operations/metadata"
"github.com/openziti-test-kitchen/zrok/rest_server_zrok/operations/share"
)
@ -77,8 +76,8 @@ func NewZrokAPI(spec *loads.Document) *ZrokAPI {
AccountInviteHandler: account.InviteHandlerFunc(func(params account.InviteParams) middleware.Responder {
return middleware.NotImplemented("operation account.Invite has not yet been implemented")
}),
InviteInviteGenerateHandler: invite.InviteGenerateHandlerFunc(func(params invite.InviteGenerateParams) middleware.Responder {
return middleware.NotImplemented("operation invite.InviteGenerate has not yet been implemented")
AdminInviteGenerateHandler: admin.InviteGenerateHandlerFunc(func(params admin.InviteGenerateParams, principal *rest_model_zrok.Principal) middleware.Responder {
return middleware.NotImplemented("operation admin.InviteGenerate has not yet been implemented")
}),
AdminListFrontendsHandler: admin.ListFrontendsHandlerFunc(func(params admin.ListFrontendsParams, principal *rest_model_zrok.Principal) middleware.Responder {
return middleware.NotImplemented("operation admin.ListFrontends has not yet been implemented")
@ -181,8 +180,8 @@ type ZrokAPI struct {
MetadataGetShareDetailHandler metadata.GetShareDetailHandler
// AccountInviteHandler sets the operation handler for the invite operation
AccountInviteHandler account.InviteHandler
// InviteInviteGenerateHandler sets the operation handler for the invite generate operation
InviteInviteGenerateHandler invite.InviteGenerateHandler
// AdminInviteGenerateHandler sets the operation handler for the invite generate operation
AdminInviteGenerateHandler admin.InviteGenerateHandler
// AdminListFrontendsHandler sets the operation handler for the list frontends operation
AdminListFrontendsHandler admin.ListFrontendsHandler
// AccountLoginHandler sets the operation handler for the login operation
@ -313,8 +312,8 @@ func (o *ZrokAPI) Validate() error {
if o.AccountInviteHandler == nil {
unregistered = append(unregistered, "account.InviteHandler")
}
if o.InviteInviteGenerateHandler == nil {
unregistered = append(unregistered, "invite.InviteGenerateHandler")
if o.AdminInviteGenerateHandler == nil {
unregistered = append(unregistered, "admin.InviteGenerateHandler")
}
if o.AdminListFrontendsHandler == nil {
unregistered = append(unregistered, "admin.ListFrontendsHandler")
@ -487,7 +486,7 @@ func (o *ZrokAPI) initHandlerCache() {
if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler)
}
o.handlers["POST"]["/invite/generate"] = invite.NewInviteGenerate(o.context, o.InviteInviteGenerateHandler)
o.handlers["POST"]["/invite/generate"] = admin.NewInviteGenerate(o.context, o.AdminInviteGenerateHandler)
if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler)
}

View File

@ -202,6 +202,28 @@ paths:
description: unauthorized
500:
description: internal server error
/invite/generate:
post:
tags:
- admin
security:
- key: []
operationId: inviteGenerate
parameters:
- name: body
in: body
schema:
$ref: "#/definitions/inviteGenerateRequest"
responses:
201:
description: invitation tokens created
400:
description: invitation tokens not created
401:
description: unauthorized
500:
description: internal server error
#
# environment
#
@ -446,27 +468,6 @@ paths:
schema:
$ref: "#/definitions/errorMessage"
#
# invite
#
/invite/generate:
post:
tags:
- invite
operationId: inviteGenerate
parameters:
- name: body
in: body
schema:
$ref: "#/definitions/inviteGenerateRequest"
responses:
201:
description: invitation tokens created
400:
description: invitation tokens not created
500:
description: internal server error
definitions:
accessRequest:
type: object

View File

@ -68,6 +68,21 @@ export function createIdentity(options) {
return gateway.request(createIdentityOperation, parameters)
}
/**
* @param {object} options Optional options
* @param {module:types.inviteGenerateRequest} [options.body]
* @return {Promise<object>} invitation tokens created
*/
export function inviteGenerate(options) {
if (!options) options = {}
const parameters = {
body: {
body: options.body
}
}
return gateway.request(inviteGenerateOperation, parameters)
}
const createFrontendOperation = {
path: '/frontend',
contentTypes: ['application/zrok.v1+json'],
@ -121,3 +136,14 @@ const createIdentityOperation = {
}
]
}
const inviteGenerateOperation = {
path: '/invite/generate',
contentTypes: ['application/zrok.v1+json'],
method: 'post',
security: [
{
id: 'key'
}
]
}

View File

@ -1,24 +0,0 @@
/** @module invite */
// Auto-generated, edits will be overwritten
import * as gateway from './gateway'
/**
* @param {object} options Optional options
* @param {module:types.inviteGenerateRequest} [options.body]
* @return {Promise<object>} invitation tokens created
*/
export function inviteGenerate(options) {
if (!options) options = {}
const parameters = {
body: {
body: options.body
}
}
return gateway.request(inviteGenerateOperation, parameters)
}
const inviteGenerateOperation = {
path: '/invite/generate',
contentTypes: ['application/zrok.v1+json'],
method: 'post'
}