2020-02-12 13:53:27 -05:00
package controller
import (
2021-04-08 20:54:32 -04:00
"bytes"
2020-02-12 13:53:27 -05:00
"context"
2020-05-21 12:12:08 -04:00
"encoding/json"
2021-07-28 06:31:16 -04:00
"errors"
2020-06-05 11:52:59 -07:00
"fmt"
2021-04-08 20:54:32 -04:00
"io/ioutil"
2020-02-12 13:53:27 -05:00
"net/http"
2021-04-08 20:54:32 -04:00
"net/textproto"
2020-07-14 14:32:47 -07:00
"os"
2020-05-12 17:35:48 -07:00
"strings"
2020-02-12 13:53:27 -05:00
"time"
2022-03-09 20:41:15 +00:00
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
2020-08-10 17:15:02 -04:00
"github.com/hashicorp/boundary/globals"
2021-05-02 15:25:29 -04:00
"github.com/hashicorp/boundary/internal/auth/oidc"
2022-05-09 12:45:10 -07:00
"github.com/hashicorp/boundary/internal/daemon/common"
"github.com/hashicorp/boundary/internal/daemon/controller/auth"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/accounts"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/authmethods"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/authtokens"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/credentiallibraries"
2022-05-18 20:20:45 -07:00
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/credentials"
2022-05-09 12:45:10 -07:00
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/credentialstores"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/groups"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/health"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/host_catalogs"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/host_sets"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/hosts"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/managed_groups"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/roles"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/scopes"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/sessions"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/targets"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/users"
2022-06-03 11:19:04 -07:00
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/workers"
2022-05-09 12:45:10 -07:00
"github.com/hashicorp/boundary/internal/daemon/controller/internal/metric"
2020-08-10 17:15:02 -04:00
"github.com/hashicorp/boundary/internal/gen/controller/api/services"
2021-10-19 17:21:41 -04:00
authpb "github.com/hashicorp/boundary/internal/gen/controller/auth"
2022-03-28 17:16:39 +01:00
opsservices "github.com/hashicorp/boundary/internal/gen/controller/ops/services"
2021-07-28 06:31:16 -04:00
"github.com/hashicorp/boundary/internal/observability/event"
2020-10-21 13:07:09 -04:00
"github.com/hashicorp/go-cleanhttp"
2021-07-14 17:50:15 -07:00
"github.com/hashicorp/go-secure-stdlib/listenerutil"
2021-07-14 17:37:40 -07:00
"github.com/hashicorp/go-secure-stdlib/strutil"
2021-10-19 17:21:41 -04:00
"github.com/mr-tron/base58"
2022-03-09 20:41:15 +00:00
"google.golang.org/grpc"
2020-12-07 14:25:16 -07:00
"google.golang.org/grpc/codes"
2021-10-19 17:21:41 -04:00
"google.golang.org/protobuf/proto"
2020-08-10 17:15:02 -04:00
2022-05-09 12:45:10 -07:00
"github.com/hashicorp/boundary/internal/daemon/controller/handlers"
2020-02-12 13:53:27 -05:00
)
type HandlerProperties struct {
2021-07-14 17:50:15 -07:00
ListenerConfig * listenerutil . ListenerConfig
2020-08-12 00:40:39 -04:00
CancelCtx context . Context
2020-02-12 13:53:27 -05:00
}
2022-03-09 20:41:15 +00:00
// apiHandler returns an http.Handler for the services. This can be used on
2020-09-25 00:55:06 +08:00
// its own to mount the Controller API within another web server.
2022-03-09 20:41:15 +00:00
func ( c * Controller ) apiHandler ( props HandlerProperties ) ( http . Handler , error ) {
2020-02-12 13:53:27 -05:00
mux := http . NewServeMux ()
2022-03-09 20:41:15 +00:00
grpcGwMux := newGrpcGatewayMux ()
err := registerGrpcGatewayEndpoints ( props . CancelCtx , grpcGwMux , gatewayDialOptions ( c . apiGrpcServerListener ) ... )
2020-06-05 11:52:59 -07:00
if err != nil {
return nil , err
}
2022-03-09 20:41:15 +00:00
mux . Handle ( "/v1/" , grpcGwMux )
2020-06-30 11:26:22 -04:00
mux . Handle ( "/" , handleUi ( c ))
2020-06-24 16:06:19 -04:00
2020-05-21 12:12:08 -04:00
corsWrappedHandler := wrapHandlerWithCors ( mux , props )
commonWrappedHandler := wrapHandlerWithCommonFuncs ( corsWrappedHandler , c , props )
2021-04-08 20:54:32 -04:00
callbackInterceptingHandler := wrapHandlerWithCallbackInterceptor ( commonWrappedHandler , c )
printablePathCheckHandler := cleanhttp . PrintablePathCheckHandler ( callbackInterceptingHandler , nil )
2021-12-09 20:41:08 -05:00
eventsHandler , err := common . WrapWithEventsHandler ( printablePathCheckHandler , c . conf . Eventer , c . kms , props . ListenerConfig )
2022-03-31 08:48:50 -07:00
if err != nil {
return nil , err
}
metricsHandler := metric . InstrumentApiHandler ( eventsHandler )
2020-02-12 13:53:27 -05:00
2022-03-31 08:48:50 -07:00
return metricsHandler , nil
2020-02-12 13:53:27 -05:00
}
2022-03-28 17:16:39 +01:00
// GetHealthHandler returns a gRPC Gateway mux that is registered against the
// controller's gRPC health service to make it accessible from an HTTP API.
func ( c * Controller ) GetHealthHandler ( lcfg * listenerutil . ListenerConfig ) ( http . Handler , error ) {
const op = "controller.(Controller).GetHealthHandler"
if lcfg == nil {
return nil , fmt . Errorf ( "%s: received nil listener config" , op )
}
healthGrpcGwMux := newGrpcGatewayMux ()
err := registerHealthGrpcGatewayEndpoint ( c . baseContext , healthGrpcGwMux , gatewayDialOptions ( c . apiGrpcServerListener ) ... )
if err != nil {
return nil , fmt . Errorf ( "%s: failed to register health service handler: %w" , op , err )
}
wrapped := wrapHandlerWithCommonFuncs ( healthGrpcGwMux , c , HandlerProperties { lcfg , c . baseContext })
return common . WrapWithEventsHandler ( wrapped , c . conf . Eventer , c . kms , lcfg )
}
func registerHealthGrpcGatewayEndpoint ( ctx context . Context , gwMux * runtime . ServeMux , dialOptions ... grpc . DialOption ) error {
return opsservices . RegisterHealthServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions )
}
2022-03-09 20:41:15 +00:00
func ( c * Controller ) registerGrpcServices ( s * grpc . Server ) error {
// We have to check against the current services because the gRPC lib treats a duplicate
// register call as an error and os.Exits.
currentServices := s . GetServiceInfo ()
2021-10-19 17:21:41 -04:00
if _ , ok := currentServices [ services . HostCatalogService_ServiceDesc . ServiceName ]; ! ok {
2021-10-21 11:47:13 -04:00
hcs , err := host_catalogs . NewService ( c . StaticHostRepoFn , c . PluginHostRepoFn , c . HostPluginRepoFn , c . IamRepoFn )
2021-10-19 17:21:41 -04:00
if err != nil {
2022-03-09 20:41:15 +00:00
return fmt . Errorf ( "failed to create host catalog handler service: %w" , err )
2021-10-19 17:21:41 -04:00
}
2022-03-09 20:41:15 +00:00
services . RegisterHostCatalogServiceServer ( s , hcs )
2020-06-09 11:20:59 -07:00
}
2021-10-19 17:21:41 -04:00
if _ , ok := currentServices [ services . HostSetService_ServiceDesc . ServiceName ]; ! ok {
2021-10-21 11:47:13 -04:00
hss , err := host_sets . NewService ( c . StaticHostRepoFn , c . PluginHostRepoFn )
2021-10-19 17:21:41 -04:00
if err != nil {
2022-03-09 20:41:15 +00:00
return fmt . Errorf ( "failed to create host set handler service: %w" , err )
2021-10-19 17:21:41 -04:00
}
2022-03-09 20:41:15 +00:00
services . RegisterHostSetServiceServer ( s , hss )
2020-09-01 15:05:46 -07:00
}
2021-10-19 17:21:41 -04:00
if _ , ok := currentServices [ services . HostService_ServiceDesc . ServiceName ]; ! ok {
2021-11-02 14:06:20 -07:00
hs , err := hosts . NewService ( c . StaticHostRepoFn , c . PluginHostRepoFn )
2021-10-19 17:21:41 -04:00
if err != nil {
2022-03-09 20:41:15 +00:00
return fmt . Errorf ( "failed to create host handler service: %w" , err )
2021-10-19 17:21:41 -04:00
}
2022-03-09 20:41:15 +00:00
services . RegisterHostServiceServer ( s , hs )
2020-09-01 15:05:46 -07:00
}
2021-10-19 17:21:41 -04:00
if _ , ok := currentServices [ services . AccountService_ServiceDesc . ServiceName ]; ! ok {
accts , err := accounts . NewService ( c . PasswordAuthRepoFn , c . OidcRepoFn )
if err != nil {
2022-03-09 20:41:15 +00:00
return fmt . Errorf ( "failed to create account handler service: %w" , err )
2021-10-19 17:21:41 -04:00
}
2022-03-09 20:41:15 +00:00
services . RegisterAccountServiceServer ( s , accts )
2020-06-15 15:22:41 -07:00
}
2021-10-19 17:21:41 -04:00
if _ , ok := currentServices [ services . AuthMethodService_ServiceDesc . ServiceName ]; ! ok {
authMethods , err := authmethods . NewService ( c . kms , c . PasswordAuthRepoFn , c . OidcRepoFn , c . IamRepoFn , c . AuthTokenRepoFn )
if err != nil {
2022-03-09 20:41:15 +00:00
return fmt . Errorf ( "failed to create auth method handler service: %w" , err )
2021-10-19 17:21:41 -04:00
}
2022-03-09 20:41:15 +00:00
services . RegisterAuthMethodServiceServer ( s , authMethods )
2020-06-15 15:22:41 -07:00
}
2021-10-19 17:21:41 -04:00
if _ , ok := currentServices [ services . AuthTokenService_ServiceDesc . ServiceName ]; ! ok {
authtoks , err := authtokens . NewService ( c . AuthTokenRepoFn , c . IamRepoFn )
if err != nil {
2022-03-09 20:41:15 +00:00
return fmt . Errorf ( "failed to create auth token handler service: %w" , err )
2021-10-19 17:21:41 -04:00
}
2022-03-09 20:41:15 +00:00
services . RegisterAuthTokenServiceServer ( s , authtoks )
2020-06-22 06:56:27 -07:00
}
2021-10-19 17:21:41 -04:00
if _ , ok := currentServices [ services . ScopeService_ServiceDesc . ServiceName ]; ! ok {
os , err := scopes . NewService ( c . IamRepoFn )
if err != nil {
2022-03-09 20:41:15 +00:00
return fmt . Errorf ( "failed to create scope handler service: %w" , err )
2021-10-19 17:21:41 -04:00
}
2022-03-09 20:41:15 +00:00
services . RegisterScopeServiceServer ( s , os )
2020-06-22 06:56:27 -07:00
}
2021-10-19 17:21:41 -04:00
if _ , ok := currentServices [ services . UserService_ServiceDesc . ServiceName ]; ! ok {
us , err := users . NewService ( c . IamRepoFn )
if err != nil {
2022-03-09 20:41:15 +00:00
return fmt . Errorf ( "failed to create user handler service: %w" , err )
2021-10-19 17:21:41 -04:00
}
2022-03-09 20:41:15 +00:00
services . RegisterUserServiceServer ( s , us )
2020-09-20 17:22:57 -07:00
}
2021-10-19 17:21:41 -04:00
if _ , ok := currentServices [ services . TargetService_ServiceDesc . ServiceName ]; ! ok {
ts , err := targets . NewService (
2022-03-09 20:41:15 +00:00
c . baseContext ,
2021-10-19 17:21:41 -04:00
c . kms ,
c . TargetRepoFn ,
c . IamRepoFn ,
c . ServersRepoFn ,
c . SessionRepoFn ,
2021-10-21 13:30:31 -04:00
c . PluginHostRepoFn ,
2021-10-19 17:21:41 -04:00
c . StaticHostRepoFn ,
2022-06-09 15:35:55 -07:00
c . VaultCredentialRepoFn ,
c . StaticCredentialRepoFn )
2021-10-19 17:21:41 -04:00
if err != nil {
2022-03-09 20:41:15 +00:00
return fmt . Errorf ( "failed to create target handler service: %w" , err )
2021-10-19 17:21:41 -04:00
}
2022-03-09 20:41:15 +00:00
services . RegisterTargetServiceServer ( s , ts )
2020-09-20 17:22:57 -07:00
}
2021-10-19 17:21:41 -04:00
if _ , ok := currentServices [ services . GroupService_ServiceDesc . ServiceName ]; ! ok {
gs , err := groups . NewService ( c . IamRepoFn )
if err != nil {
2022-03-09 20:41:15 +00:00
return fmt . Errorf ( "failed to create group handler service: %w" , err )
2021-10-19 17:21:41 -04:00
}
2022-03-09 20:41:15 +00:00
services . RegisterGroupServiceServer ( s , gs )
2021-06-02 13:01:37 -05:00
}
2021-10-19 17:21:41 -04:00
if _ , ok := currentServices [ services . RoleService_ServiceDesc . ServiceName ]; ! ok {
rs , err := roles . NewService ( c . IamRepoFn )
if err != nil {
2022-03-09 20:41:15 +00:00
return fmt . Errorf ( "failed to create role handler service: %w" , err )
2021-10-19 17:21:41 -04:00
}
2022-03-09 20:41:15 +00:00
services . RegisterRoleServiceServer ( s , rs )
2021-06-02 13:01:37 -05:00
}
2021-10-19 17:21:41 -04:00
if _ , ok := currentServices [ services . SessionService_ServiceDesc . ServiceName ]; ! ok {
ss , err := sessions . NewService ( c . SessionRepoFn , c . IamRepoFn )
if err != nil {
2022-03-09 20:41:15 +00:00
return fmt . Errorf ( "failed to create session handler service: %w" , err )
2021-10-19 17:21:41 -04:00
}
2022-03-09 20:41:15 +00:00
services . RegisterSessionServiceServer ( s , ss )
2021-06-22 22:26:26 -04:00
}
2021-10-19 17:21:41 -04:00
if _ , ok := currentServices [ services . ManagedGroupService_ServiceDesc . ServiceName ]; ! ok {
mgs , err := managed_groups . NewService ( c . OidcRepoFn )
if err != nil {
2022-03-09 20:41:15 +00:00
return fmt . Errorf ( "failed to create managed groups handler service: %w" , err )
2021-10-19 17:21:41 -04:00
}
2022-03-09 20:41:15 +00:00
services . RegisterManagedGroupServiceServer ( s , mgs )
2021-06-22 22:26:26 -04:00
}
2021-10-19 17:21:41 -04:00
if _ , ok := currentServices [ services . CredentialStoreService_ServiceDesc . ServiceName ]; ! ok {
2022-08-25 14:37:22 -04:00
cs , err := credentialstores . NewService ( c . baseContext , c . VaultCredentialRepoFn , c . StaticCredentialRepoFn , c . IamRepoFn )
2021-10-19 17:21:41 -04:00
if err != nil {
2022-03-09 20:41:15 +00:00
return fmt . Errorf ( "failed to create credential store handler service: %w" , err )
2021-10-19 17:21:41 -04:00
}
2022-03-09 20:41:15 +00:00
services . RegisterCredentialStoreServiceServer ( s , cs )
2021-06-22 22:26:26 -04:00
}
2021-10-19 17:21:41 -04:00
if _ , ok := currentServices [ services . CredentialLibraryService_ServiceDesc . ServiceName ]; ! ok {
cl , err := credentiallibraries . NewService ( c . VaultCredentialRepoFn , c . IamRepoFn )
if err != nil {
2022-03-09 20:41:15 +00:00
return fmt . Errorf ( "failed to create credential library handler service: %w" , err )
2021-10-19 17:21:41 -04:00
}
2022-03-09 20:41:15 +00:00
services . RegisterCredentialLibraryServiceServer ( s , cl )
}
2022-06-03 11:19:04 -07:00
if _ , ok := currentServices [ services . WorkerService_ServiceDesc . ServiceName ]; ! ok {
ws , err := workers . NewService ( c . baseContext , c . ServersRepoFn , c . IamRepoFn )
if err != nil {
return fmt . Errorf ( "failed to create worker handler service: %w" , err )
}
services . RegisterWorkerServiceServer ( s , ws )
}
2022-05-18 20:20:45 -07:00
if _ , ok := currentServices [ services . CredentialService_ServiceDesc . ServiceName ]; ! ok {
c , err := credentials . NewService ( c . StaticCredentialRepoFn , c . IamRepoFn )
if err != nil {
return fmt . Errorf ( "failed to create credential handler service: %w" , err )
}
services . RegisterCredentialServiceServer ( s , c )
}
2022-03-28 17:16:39 +01:00
if _ , ok := s . GetServiceInfo ()[ opsservices . HealthService_ServiceDesc . ServiceName ]; ! ok {
hs := health . NewService ()
opsservices . RegisterHealthServiceServer ( s , hs )
c . HealthService = hs
}
2022-03-09 20:41:15 +00:00
return nil
}
func registerGrpcGatewayEndpoints ( ctx context . Context , gwMux * runtime . ServeMux , dialOptions ... grpc . DialOption ) error {
// Register*ServiceHandlerServer methods ignore the passed in context.
// Passing it in anyways in case this changes in the future.
if err := services . RegisterHostCatalogServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register host catalog service handler: %w" , err )
}
if err := services . RegisterHostSetServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register host set service handler: %w" , err )
}
if err := services . RegisterHostServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register host service handler: %w" , err )
}
if err := services . RegisterAccountServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register account service handler: %w" , err )
}
if err := services . RegisterAuthMethodServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register auth method service handler: %w" , err )
}
if err := services . RegisterAuthTokenServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register auth token service handler: %w" , err )
}
if err := services . RegisterScopeServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register scope service handler: %w" , err )
}
if err := services . RegisterUserServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register user service handler: %w" , err )
}
if err := services . RegisterTargetServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register target service handler: %w" , err )
}
if err := services . RegisterGroupServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register group service handler: %w" , err )
}
if err := services . RegisterRoleServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register role service handler: %w" , err )
}
if err := services . RegisterSessionServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register session service handler: %w" , err )
}
if err := services . RegisterManagedGroupServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register managed groups service handler: %w" , err )
}
if err := services . RegisterCredentialStoreServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register credential store service handler: %w" , err )
}
if err := services . RegisterCredentialLibraryServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register credential library service handler: %w" , err )
2021-06-22 22:26:26 -04:00
}
2022-06-03 11:19:04 -07:00
if err := services . RegisterWorkerServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register worker service handler: %w" , err )
}
2022-05-18 20:20:45 -07:00
if err := services . RegisterCredentialServiceHandlerFromEndpoint ( ctx , gwMux , gatewayTarget , dialOptions ); err != nil {
return fmt . Errorf ( "failed to register credential service handler: %w" , err )
}
2020-05-01 12:38:01 -07:00
2022-03-09 20:41:15 +00:00
return nil
2020-02-12 13:53:27 -05:00
}
2020-05-21 12:12:08 -04:00
func wrapHandlerWithCommonFuncs ( h http . Handler , c * Controller , props HandlerProperties ) http . Handler {
2021-07-28 06:31:16 -04:00
const op = "controller.wrapHandlerWithCommonFuncs"
2020-02-12 13:53:27 -05:00
var maxRequestDuration time . Duration
var maxRequestSize int64
if props . ListenerConfig != nil {
maxRequestDuration = props . ListenerConfig . MaxRequestDuration
maxRequestSize = props . ListenerConfig . MaxRequestSize
}
if maxRequestDuration == 0 {
maxRequestDuration = globals . DefaultMaxRequestDuration
}
if maxRequestSize == 0 {
maxRequestSize = globals . DefaultMaxRequestSize
}
2020-07-14 14:32:47 -07:00
disableAuthzFailures := c . conf . DisableAuthorizationFailures ||
2020-08-10 17:15:02 -04:00
( c . conf . RawConfig . DevController && os . Getenv ( "BOUNDARY_DEV_SKIP_AUTHZ" ) != "" )
2020-07-14 14:32:47 -07:00
if disableAuthzFailures {
2021-07-28 06:31:16 -04:00
event . WriteSysEvent ( context . TODO (), op , "AUTHORIZATION CHECKING DISABLED" )
2020-05-12 17:35:48 -07:00
}
2020-07-14 14:32:47 -07:00
2020-02-12 13:53:27 -05:00
return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
// Set the Cache-Control header for all responses returned
w . Header (). Set ( "Cache-Control" , "no-store" )
2020-07-14 14:32:47 -07:00
// Start with the request context and our timeout
ctx , cancelFunc := context . WithTimeout ( r . Context (), maxRequestDuration )
defer cancelFunc ()
2020-02-12 13:53:27 -05:00
// Add a size limiter if desired
if maxRequestSize > 0 {
2020-08-20 13:34:03 -04:00
ctx = context . WithValue ( ctx , globals . ContextMaxRequestSizeTypeKey , maxRequestSize )
2020-02-12 13:53:27 -05:00
}
2020-07-16 22:12:26 -04:00
// Add values for authn/authz checking
2021-10-19 17:21:41 -04:00
requestInfo := authpb . RequestInfo {
2020-07-16 22:12:26 -04:00
Path : r . URL . Path ,
Method : r . Method ,
DisableAuthzFailures : disableAuthzFailures ,
}
2020-08-20 13:34:03 -04:00
2021-07-28 06:31:16 -04:00
requestInfo . PublicId , requestInfo . EncryptedToken , requestInfo . TokenFormat = auth . GetTokenFromRequest ( ctx , c . kms , r )
2020-07-16 22:12:26 -04:00
2021-10-23 21:23:49 -04:00
if info , ok := event . RequestInfoFromContext ( ctx ); ok {
// piggyback some eventing fields with the auth info proto message
requestInfo . EventId = info . EventId
requestInfo . TraceId = info . Id
2021-12-09 20:41:08 -05:00
requestInfo . ClientIp = info . ClientIp
2021-10-23 21:23:49 -04:00
} else {
w . WriteHeader ( http . StatusInternalServerError )
event . WriteError ( ctx , op , errors . New ( "unable to read event request info from context" ))
return
}
2021-10-19 17:21:41 -04:00
// Serialize the request info to send it across the wire to the
// grpc-gateway via an http header
2022-03-09 20:41:15 +00:00
requestInfo . Ticket = c . apiGrpcGatewayTicket // allows the grpc-gateway to verify the request info came from it's in-memory companion http proxy
2021-10-19 17:21:41 -04:00
marshalledRequestInfo , err := proto . Marshal ( & requestInfo )
if err != nil {
event . WriteError ( ctx , op , err , event . WithInfoMsg ( "error marshaling request info" ))
w . WriteHeader ( http . StatusInternalServerError )
return
}
// Use the default grpc-gateway mapping rule to pass the request info as
// metadata.
// See: https://pkg.go.dev/github.com/grpc-ecosystem/grpc-gateway/runtime#DefaultHeaderMatcher
r . Header . Set ( "Grpc-Metadata-" + requestInfoMdKey , base58 . FastBase58Encoding ( marshalledRequestInfo ))
2020-02-12 13:53:27 -05:00
2021-10-23 21:23:49 -04:00
// Set the context back on the request
2022-04-15 13:28:17 -04:00
r = r . Clone ( ctx )
2020-02-12 13:53:27 -05:00
h . ServeHTTP ( w , r )
})
}
2020-05-21 12:12:08 -04:00
func wrapHandlerWithCors ( h http . Handler , props HandlerProperties ) http . Handler {
allowedMethods := [] string {
http . MethodDelete ,
http . MethodGet ,
http . MethodOptions ,
http . MethodPost ,
http . MethodPatch ,
}
allowedOrigins := props . ListenerConfig . CorsAllowedOrigins
allowedHeaders := append ([] string {
"Content-Type" ,
"X-Requested-With" ,
"Authorization" ,
}, props . ListenerConfig . CorsAllowedHeaders ... )
return http . HandlerFunc ( func ( w http . ResponseWriter , req * http . Request ) {
2021-02-11 20:10:48 -05:00
if props . ListenerConfig . CorsEnabled == nil || ! * props . ListenerConfig . CorsEnabled {
2020-05-21 12:12:08 -04:00
h . ServeHTTP ( w , req )
return
}
origin := req . Header . Get ( "Origin" )
if origin == "" {
// Serve directly
h . ServeHTTP ( w , req )
return
}
// Check origin
var valid bool
switch {
case len ( allowedOrigins ) == 0 :
// not valid
2021-04-15 12:33:52 -05:00
case len ( allowedOrigins ) == 1 && allowedOrigins [ 0 ] == "*" :
2020-05-21 12:12:08 -04:00
valid = true
2022-07-25 14:05:00 -04:00
// When allowed origins is "*" we want to return that rather than
// round-tripping any user-specified value
origin = "*"
2020-05-21 12:12:08 -04:00
default :
valid = strutil . StrListContains ( allowedOrigins , origin )
}
2021-02-12 11:04:09 -05:00
2020-05-21 12:12:08 -04:00
if ! valid {
w . Header (). Set ( "Content-Type" , "application/json" )
w . WriteHeader ( http . StatusForbidden )
2020-12-07 14:25:16 -07:00
err := handlers . ApiErrorWithCodeAndMessage ( codes . PermissionDenied , "origin forbidden" )
2020-05-21 12:12:08 -04:00
enc := json . NewEncoder ( w )
2021-07-28 06:31:16 -04:00
_ = enc . Encode ( err )
2020-05-21 12:12:08 -04:00
return
}
if req . Method == http . MethodOptions &&
! strutil . StrListContains ( allowedMethods , req . Header . Get ( "Access-Control-Request-Method" )) {
w . WriteHeader ( http . StatusMethodNotAllowed )
return
}
w . Header (). Set ( "Access-Control-Allow-Origin" , origin )
w . Header (). Set ( "Vary" , "Origin" )
// Apply headers for preflight requests
if req . Method == http . MethodOptions {
w . Header (). Set ( "Access-Control-Allow-Methods" , strings . Join ( allowedMethods , ", " ))
w . Header (). Set ( "Access-Control-Allow-Headers" , strings . Join ( allowedHeaders , ", " ))
w . Header (). Set ( "Access-Control-Max-Age" , "300" )
w . WriteHeader ( http . StatusNoContent )
return
}
h . ServeHTTP ( w , req )
})
}
2021-04-08 20:54:32 -04:00
type cmdAttrs struct {
Command string `json:"command,omitempty"`
Attributes interface {} `json:"attributes,omitempty"`
}
func wrapHandlerWithCallbackInterceptor ( h http . Handler , c * Controller ) http . Handler {
logCallbackErrors := os . Getenv ( "BOUNDARY_LOG_CALLBACK_ERRORS" ) != ""
return http . HandlerFunc ( func ( w http . ResponseWriter , req * http . Request ) {
2021-07-28 06:31:16 -04:00
const op = "controller.wrapHandlerWithCallbackInterceptor"
ctx := req . Context ()
var err error
id , err := event . NewId ( event . IdField )
if err != nil {
w . WriteHeader ( http . StatusInternalServerError )
event . WriteError ( ctx , op , err , event . WithInfoMsg ( "unable to create id for event" , "method" , req . Method , "url" , req . URL . RequestURI ()))
return
}
info := & event . RequestInfo {
EventId : id ,
Id : common . GeneratedTraceId ( ctx ),
PublicId : "unknown" ,
Method : req . Method ,
Path : req . URL . RequestURI (),
}
ctx , err = event . NewRequestInfoContext ( ctx , info )
if err != nil {
w . WriteHeader ( http . StatusInternalServerError )
event . WriteError ( req . Context (), op , err , event . WithInfoMsg ( "unable to create context with request info" , "method" , req . Method , "url" , req . URL . RequestURI ()))
return
}
2021-04-08 20:54:32 -04:00
// If this doesn't have a callback suffix on a supported action, serve
// normally
if ! strings . HasSuffix ( req . URL . Path , ":authenticate:callback" ) {
h . ServeHTTP ( w , req )
return
}
req . URL . Path = strings . TrimSuffix ( req . URL . Path , ":callback" )
// How we get the parameters changes based on the method. Right now only
// GET is supported with query args, but this can support POST with JSON
// or URL-encoded args. In those cases, the MIME type would have to be
// checked; for URL-encoded it'd use ParseForm like Get, and for JSON
// you'd use a json.RawMessage for Attributes consisting of the body. Or
// something very similar to that.
var useForm bool
switch req . Method {
case http . MethodGet :
if err := req . ParseForm (); err != nil {
if logCallbackErrors && c != nil {
2021-07-28 06:31:16 -04:00
event . WriteError ( ctx , op , err , event . WithInfoMsg ( "callback error" ))
2021-04-08 20:54:32 -04:00
}
w . WriteHeader ( http . StatusBadRequest )
return
}
useForm = true
}
attrs := & cmdAttrs {
Command : "callback" ,
}
switch {
case useForm :
if len ( req . Form ) > 0 {
values := make ( map [ string ] interface {}, len ( req . Form ))
// This won't handle repeated values. That's fine, at least for now.
// We can address that if needed, which seems unlikely.
for k := range req . Form {
values [ k ] = req . Form . Get ( k )
}
2021-05-02 15:25:29 -04:00
if strings . HasSuffix ( req . URL . Path , "oidc:authenticate" ) {
if s , ok := values [ "state" ].( string ); ok {
stateWrapper , err := oidc . UnwrapMessage ( context . Background (), s )
if err != nil {
2021-07-28 06:31:16 -04:00
event . WriteError ( ctx , op , err , event . WithInfoMsg ( "error marshaling state" ))
2021-05-02 15:25:29 -04:00
w . WriteHeader ( http . StatusInternalServerError )
return
}
if stateWrapper . AuthMethodId == "" {
2021-07-28 06:31:16 -04:00
event . WriteError ( ctx , op , err , event . WithInfoMsg ( "missing auth method id" ))
2021-05-02 15:25:29 -04:00
w . WriteHeader ( http . StatusInternalServerError )
return
}
stripped := strings . TrimSuffix ( req . URL . Path , "oidc:authenticate" )
req . URL . Path = fmt . Sprintf ( "%s%s:authenticate" , stripped , stateWrapper . AuthMethodId )
} else {
2021-07-28 06:31:16 -04:00
event . WriteError ( ctx , op , errors . New ( "missing state parameter" ))
2021-05-02 15:25:29 -04:00
w . WriteHeader ( http . StatusInternalServerError )
return
}
}
2021-04-08 20:54:32 -04:00
attrs . Attributes = values
}
attrBytes , err := json . Marshal ( attrs )
if err != nil {
if logCallbackErrors && c != nil {
2021-07-28 06:31:16 -04:00
event . WriteError ( ctx , op , err , event . WithInfoMsg ( "error marshaling json" ))
2021-04-08 20:54:32 -04:00
}
w . WriteHeader ( http . StatusInternalServerError )
return
}
// If there is any existing body, close it as we're going to replace
// it. It shouldn't be populated in this code path, but you never
// know.
if req . Body != nil {
if err := req . Body . Close (); err != nil {
if logCallbackErrors && c != nil {
2021-07-28 06:31:16 -04:00
event . WriteError ( ctx , op , err , event . WithInfoMsg ( "error closing original request body" ))
2021-04-08 20:54:32 -04:00
}
}
}
bytesReader := bytes . NewReader ( attrBytes )
req . Body = ioutil . NopCloser ( bytesReader )
req . ContentLength = int64 ( bytesReader . Len ())
req . Header . Set ( textproto . CanonicalMIMEHeaderKey ( "content-type" ), "application/json" )
req . Method = http . MethodPost
}
h . ServeHTTP ( w , req )
})
}
2020-02-12 13:53:27 -05:00
/*
func WrapForwardedForHandler(h http.Handler, authorizedAddrs []*sockaddr.SockAddrMarshaler, rejectNotPresent, rejectNonAuthz bool, hopSkips int) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
headers, headersOK := r.Header[textproto.CanonicalMIMEHeaderKey("X-Forwarded-For")]
if !headersOK || len(headers) == 0 {
if !rejectNotPresent {
h.ServeHTTP(w, r)
return
}
respondError(w, http.StatusBadRequest, fmt.Errorf("missing x-forwarded-for header and configured to reject when not present"))
return
}
host, port, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
// If not rejecting treat it like we just don't have a valid
// header because we can't do a comparison against an address we
// can't understand
if !rejectNotPresent {
h.ServeHTTP(w, r)
return
}
respondError(w, http.StatusBadRequest, errwrap.Wrapf("error parsing client hostport: {{err}}", err))
return
}
addr, err := sockaddr.NewIPAddr(host)
if err != nil {
// We treat this the same as the case above
if !rejectNotPresent {
h.ServeHTTP(w, r)
return
}
respondError(w, http.StatusBadRequest, errwrap.Wrapf("error parsing client address: {{err}}", err))
return
}
var found bool
for _, authz := range authorizedAddrs {
if authz.Contains(addr) {
found = true
break
}
}
if !found {
// If we didn't find it and aren't configured to reject, simply
// don't trust it
if !rejectNonAuthz {
h.ServeHTTP(w, r)
return
}
respondError(w, http.StatusBadRequest, fmt.Errorf("client address not authorized for x-forwarded-for and configured to reject connection"))
return
}
// At this point we have at least one value and it's authorized
// Split comma separated ones, which are common. This brings it in line
// to the multiple-header case.
var acc []string
for _, header := range headers {
vals := strings.Split(header, ",")
for _, v := range vals {
acc = append(acc, strings.TrimSpace(v))
}
}
indexToUse := len(acc) - 1 - hopSkips
if indexToUse < 0 {
// This is likely an error in either configuration or other
// infrastructure. We could either deny the request, or we
// could simply not trust the value. Denying the request is
// "safer" since if this logic is configured at all there may
// be an assumption it can always be trusted. Given that we can
// deny accepting the request at all if it's not from an
// authorized address, if we're at this point the address is
// authorized (or we've turned off explicit rejection) and we
// should assume that what comes in should be properly
// formatted.
respondError(w, http.StatusBadRequest, fmt.Errorf("malformed x-forwarded-for configuration or request, hops to skip (%d) would skip before earliest chain link (chain length %d)", hopSkips, len(headers)))
return
}
r.RemoteAddr = net.JoinHostPort(acc[indexToUse], port)
h.ServeHTTP(w, r)
return
})
}
*/