Skip to content
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

feature(gateway,pkg): add connector service requirements #3840

Merged
merged 4 commits into from
Jul 22, 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
2 changes: 2 additions & 0 deletions api/pkg/echo/handlers/pkg/converter/converter.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
// FromErrServiceToHTTPStatus converts a service error code to http status.
func FromErrServiceToHTTPStatus(code int) int {
switch code {
case services.ErrCodeCreated:
return http.StatusCreated
case services.ErrCodeNotFound:
return http.StatusNotFound
case services.ErrCodeInvalid:
Expand Down
2 changes: 2 additions & 0 deletions api/services/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ const (
// ErrCodeNoContentChange is the error that occurs when the store function does not change any resource. Generally used in
// update methods.
ErrCodeNoContentChange
// ErrCodeCreated is the error code to be used when the resource was created, but the following operations failed.
ErrCodeCreated
)

// ErrDataNotFound structure should be used to add errors.Data to an error when the resource is not found.
Expand Down
18 changes: 18 additions & 0 deletions gateway/conf.d/shellhub.conf
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,24 @@ server {
}
{{ end -}}

{{ if bool (env.Getenv "SHELLHUB_CLOUD") -}}
location /api/connector {
set $upstream cloud-api:8080;
auth_request /auth;
auth_request_set $tenant_id $upstream_http_x_tenant_id;
auth_request_set $username $upstream_http_x_username;
auth_request_set $id $upstream_http_x_id;
auth_request_set $role $upstream_http_x_role;
error_page 500 =401 /auth;
rewrite ^/api/(.*)$ /api/$1 break;
proxy_set_header X-Tenant-ID $tenant_id;
proxy_set_header X-Username $username;
proxy_set_header X-ID $id;
proxy_set_header X-Role $role;
proxy_pass http://$upstream;
}
{{ end -}}

{{ if bool (env.Getenv "SHELLHUB_ENTERPRISE") -}}
location /api/firewall {
set $upstream cloud-api:8080;
Expand Down
10 changes: 10 additions & 0 deletions pkg/agent/connector/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,16 @@ func LoadConfigFromEnv() (*Config, map[string]interface{}, error) {
return cfg, nil, nil
}

func NewDockerConnectorWithClient(cli *dockerclient.Client, server string, tenant string, privateKey string) (Connector, error) {
return &DockerConnector{
server: server,
tenant: tenant,
cli: cli,
privateKeys: privateKey,
cancels: make(map[string]context.CancelFunc),
}, nil
}

// NewDockerConnector creates a new [Connector] that uses Docker as the container runtime.
func NewDockerConnector(server string, tenant string, privateKey string) (Connector, error) {
cli, err := dockerclient.NewClientWithOpts(dockerclient.FromEnv, dockerclient.WithAPIVersionNegotiation())
Expand Down
2 changes: 2 additions & 0 deletions pkg/agent/modes.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ func (m *HostMode) Serve(agent *Agent) {
&server.Config{
PrivateKey: agent.config.PrivateKey,
KeepAliveInterval: agent.config.KeepAliveInterval,
Features: server.LocalPortForwardFeature,
},
)

Expand Down Expand Up @@ -98,6 +99,7 @@ func (m *ConnectorMode) Serve(agent *Agent) {
&server.Config{
PrivateKey: agent.config.PrivateKey,
KeepAliveInterval: agent.config.KeepAliveInterval,
Features: server.NoFeature,
},
)

Expand Down
17 changes: 15 additions & 2 deletions pkg/agent/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,25 @@ const (
ChannelDirectTcpip string = "direct-tcpip"
)

type Feature uint

const (
// NoFeature no features enable.
NoFeature Feature = 0
// LocalPortForwardFeature enable local port forward feature.
LocalPortForwardFeature Feature = iota << 1
// ReversePortForwardFeature enable reverse port forward feature.
ReversePortForwardFeature
)

// Config stores configuration needs for the SSH server.
type Config struct {
// PrivateKey is the path for the SSH server private key.
PrivateKey string
// KeepAliveInterval stores the time between each SSH keep alive request.
KeepAliveInterval uint
// Features list of featues on SSH server.
Features Feature
}

// NewServer creates a new server SSH agent server.
Expand Down Expand Up @@ -120,10 +133,10 @@ func NewServer(api client.Client, mode modes.Mode, cfg *Config) *Server {
return &sshConn{conn, closeCallback, ctx}
},
LocalPortForwardingCallback: func(ctx gliderssh.Context, destinationHost string, destinationPort uint32) bool {
return true
return cfg.Features&LocalPortForwardFeature > 0
},
ReversePortForwardingCallback: func(ctx gliderssh.Context, destinationHost string, destinationPort uint32) bool {
return false
return cfg.Features&ReversePortForwardFeature > 0
},
ChannelHandlers: map[string]gliderssh.ChannelHandler{
ChannelSession: gliderssh.DefaultSessionHandler,
Expand Down
12 changes: 12 additions & 0 deletions pkg/api/authorizer/permissions.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ const (
APIKeyCreate
APIKeyUpdate
APIKeyDelete

ConnectorDelete
ConnectorUpdate
ConnectorSet
)

var observerPermissions = []Permission{
Expand Down Expand Up @@ -122,6 +126,10 @@ var adminPermissions = []Permission{
APIKeyCreate,
APIKeyUpdate,
APIKeyDelete,

ConnectorDelete,
ConnectorUpdate,
ConnectorSet,
}

var ownerPermissions = []Permission{
Expand Down Expand Up @@ -176,4 +184,8 @@ var ownerPermissions = []Permission{
APIKeyCreate,
APIKeyUpdate,
APIKeyDelete,

ConnectorDelete,
ConnectorUpdate,
ConnectorSet,
}
6 changes: 6 additions & 0 deletions pkg/api/authorizer/role_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ func TestRolePermissions(t *testing.T) {
authorizer.APIKeyCreate,
authorizer.APIKeyUpdate,
authorizer.APIKeyDelete,
authorizer.ConnectorDelete,
authorizer.ConnectorUpdate,
authorizer.ConnectorSet,
},
},
{
Expand Down Expand Up @@ -149,6 +152,9 @@ func TestRolePermissions(t *testing.T) {
authorizer.APIKeyCreate,
authorizer.APIKeyUpdate,
authorizer.APIKeyDelete,
authorizer.ConnectorDelete,
authorizer.ConnectorUpdate,
authorizer.ConnectorSet,
},
},
{
Expand Down
41 changes: 41 additions & 0 deletions pkg/models/connector.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package models

type ConnectorStatus struct {
// State of connection.
State string `json:"state" bson:"state"`
// Message contains a message what caused the current [State].
Message string `json:"message" bson:"message"`
}

type ConnectorTLS struct {
// CA is the Certificate Authority used to generate the [Cert] for the server and the client.
CA string `json:"ca" bson:"ca" validate:"required,certPEM"`
// Cert is generated from [CA] certificate and used by the client to authorize the connection to the Container Engine.
Cert string `json:"cert" bson:"cert" validate:"required,certPEM"`
// Key is the private key for the certificate on [Cert] field.
Key string `json:"key" bson:"key" validate:"required,privateKeyPEM"`
}

// ConnectorData contains the mutable data for each Connector.
type ConnectorData struct {
// Enable indicates if the Connection's connection is enable.
Enable *bool `json:"enable" bson:"enable,omitempty"`
// Secure indicates if the Connector use HTTPS for authentication.
Secure *bool `json:"secure" bson:"secure,omitempty"`
// Address is the address to the Container Engine.
Address *string `json:"address" bson:"address,omitempty" validate:"required,hostname_rfc1123"`
// Port is the port to Container Engine.
Port *uint `json:"port" bson:"port,omitempty" validate:"required,min=1,max=65535"`
// TLS stores the configuration for authenticate using TLS on the Container Engine.
TLS *ConnectorTLS `json:"tls,omitempty" bson:"tls,omitempty" validate:"required_if=Secure true"`
}

type Connector struct {
// UID is the unique identifier of Connector.
UID string `json:"uid" bson:"uid"`
// TenantID indicate which namespace this connector is related.
TenantID string `json:"tenant_id" bson:"tenant_id"`
// Status shows the connection status for the connector.
Status ConnectorStatus `json:"status" bson:"-"`
ConnectorData `bson:",inline"`
}
33 changes: 33 additions & 0 deletions pkg/validator/validator.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package validator

import (
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"reflect"
Expand Down Expand Up @@ -37,6 +39,9 @@ const (
UserPasswordTag = "password"
// DeviceNameTag contains the rule to validate the device's name.
DeviceNameTag = "device_name"
// PrivateKeyPEMTag contains the rule to validate a private key.
PrivateKeyPEMTag = "privateKeyPEM"
CertPEMTag = "certPEM"
)

// Rules is a slice that contains all validation rules.
Expand Down Expand Up @@ -121,6 +126,34 @@ var Rules = []Rule{
},
Error: fmt.Errorf("role must be \"owner\", \"administrator\", \"operator\" or \"observer\""),
},
{
Tag: PrivateKeyPEMTag,
Handler: func(field validator.FieldLevel) bool {
block, _ := pem.Decode([]byte(field.Field().String()))
if block == nil {
return false
}

key, err := x509.ParsePKCS8PrivateKey(block.Bytes)

return err == nil && key != nil
},
Error: fmt.Errorf("the private key is invalid"),
},
{
Tag: CertPEMTag,
Handler: func(field validator.FieldLevel) bool {
block, _ := pem.Decode([]byte(field.Field().String()))
if block == nil {
return false
}

cert, err := x509.ParseCertificate(block.Bytes)

return err == nil && cert != nil
},
Error: fmt.Errorf("the cert is invalid"),
},
}

// Validator is the ShellHub validator.
Expand Down
Loading
Loading