Skip to content
This repository has been archived by the owner on Nov 14, 2024. It is now read-only.

Tweak AS registration check and AS component HTTP clients #1785

Merged
merged 11 commits into from
Mar 5, 2021
11 changes: 4 additions & 7 deletions appservice/appservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ package appservice

import (
"context"
"net/http"
"sync"
"time"

"github.com/gorilla/mux"
appserviceAPI "github.com/matrix-org/dendrite/appservice/api"
Expand Down Expand Up @@ -48,6 +46,7 @@ func NewInternalAPI(
userAPI userapi.UserInternalAPI,
rsAPI roomserverAPI.RoomserverInternalAPI,
) appserviceAPI.AppServiceQueryAPI {
client := base.CreateAppserviceClient()
consumer, _ := kafka.SetupConsumerProducer(&base.Cfg.Global.Kafka)

// Create a connection to the appservice postgres DB
Expand Down Expand Up @@ -79,10 +78,8 @@ func NewInternalAPI(
// Create appserivce query API with an HTTP client that will be used for all
// outbound and inbound requests (inbound only for the internal API)
appserviceQueryAPI := &query.AppServiceQueryAPI{
HTTPClient: &http.Client{
Timeout: time.Second * 30,
},
Cfg: base.Cfg,
HTTPClient: client,
Cfg: base.Cfg,
}

// Only consume if we actually have ASes to track, else we'll just chew cycles needlessly.
Expand All @@ -98,7 +95,7 @@ func NewInternalAPI(
}

// Create application service transaction workers
if err := workers.SetupTransactionWorkers(appserviceDB, workerStates); err != nil {
if err := workers.SetupTransactionWorkers(client, appserviceDB, workerStates); err != nil {
logrus.WithError(err).Panicf("failed to start app service transaction workers")
}
return appserviceQueryAPI
Expand Down
17 changes: 4 additions & 13 deletions appservice/query/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (

"github.com/matrix-org/dendrite/appservice/api"
"github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/gomatrixserverlib"
opentracing "github.com/opentracing/opentracing-go"
log "github.com/sirupsen/logrus"
)
Expand All @@ -33,7 +34,7 @@ const userIDExistsPath = "/users/"

// AppServiceQueryAPI is an implementation of api.AppServiceQueryAPI
type AppServiceQueryAPI struct {
HTTPClient *http.Client
HTTPClient *gomatrixserverlib.Client
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we using this client instead of a normal one? GMSL.Client is for federation traffic only I thought? ASes do not get sent signed traffic.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

gomatrixserverlib.Client is for normal requests (like what the media API uses to fetch media), gomatrixserverlib.FederationClient is for signed requests.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the difference between GMSL.Client and net/http.Client?

Copy link
Contributor Author

@neilalexander neilalexander Mar 4, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not much, mostly just that gomatrixserverlib.Client has all of the correct wiring already to give it a timeout and/or disable TLS validation without needing to reinvent the wheel again in the AS code.

Cfg *config.Dendrite
}

Expand All @@ -47,11 +48,6 @@ func (a *AppServiceQueryAPI) RoomAliasExists(
span, ctx := opentracing.StartSpanFromContext(ctx, "ApplicationServiceRoomAlias")
defer span.Finish()

// Create an HTTP client if one does not already exist
if a.HTTPClient == nil {
a.HTTPClient = makeHTTPClient()
}

// Determine which application service should handle this request
for _, appservice := range a.Cfg.Derived.ApplicationServices {
if appservice.URL != "" && appservice.IsInterestedInRoomAlias(request.Alias) {
Expand All @@ -68,7 +64,7 @@ func (a *AppServiceQueryAPI) RoomAliasExists(
}
req = req.WithContext(ctx)

resp, err := a.HTTPClient.Do(req)
resp, err := a.HTTPClient.DoHTTPRequest(ctx, req)
if resp != nil {
defer func() {
err = resp.Body.Close()
Expand Down Expand Up @@ -115,11 +111,6 @@ func (a *AppServiceQueryAPI) UserIDExists(
span, ctx := opentracing.StartSpanFromContext(ctx, "ApplicationServiceUserID")
defer span.Finish()

// Create an HTTP client if one does not already exist
if a.HTTPClient == nil {
a.HTTPClient = makeHTTPClient()
}

// Determine which application service should handle this request
for _, appservice := range a.Cfg.Derived.ApplicationServices {
if appservice.URL != "" && appservice.IsInterestedInUserID(request.UserID) {
Expand All @@ -134,7 +125,7 @@ func (a *AppServiceQueryAPI) UserIDExists(
if err != nil {
return err
}
resp, err := a.HTTPClient.Do(req.WithContext(ctx))
resp, err := a.HTTPClient.DoHTTPRequest(ctx, req)
if resp != nil {
defer func() {
err = resp.Body.Close()
Expand Down
16 changes: 5 additions & 11 deletions appservice/workers/transaction_scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ import (
var (
// Maximum size of events sent in each transaction.
transactionBatchSize = 50
// Timeout for sending a single transaction to an application service.
transactionTimeout = time.Second * 60
)

// SetupTransactionWorkers spawns a separate goroutine for each application
Expand All @@ -44,32 +42,28 @@ var (
// size), then send that off to the AS's /transactions/{txnID} endpoint. It also
// handles exponentially backing off in case the AS isn't currently available.
func SetupTransactionWorkers(
client *gomatrixserverlib.Client,
appserviceDB storage.Database,
workerStates []types.ApplicationServiceWorkerState,
) error {
// Create a worker that handles transmitting events to a single homeserver
for _, workerState := range workerStates {
// Don't create a worker if this AS doesn't want to receive events
if workerState.AppService.URL != "" {
go worker(appserviceDB, workerState)
go worker(client, appserviceDB, workerState)
}
}
return nil
}

// worker is a goroutine that sends any queued events to the application service
// it is given.
func worker(db storage.Database, ws types.ApplicationServiceWorkerState) {
func worker(client *gomatrixserverlib.Client, db storage.Database, ws types.ApplicationServiceWorkerState) {
log.WithFields(log.Fields{
"appservice": ws.AppService.ID,
}).Info("Starting application service")
ctx := context.Background()

// Create a HTTP client for sending requests to app services
client := &http.Client{
Timeout: transactionTimeout,
}

// Initial check for any leftover events to send from last time
eventCount, err := db.CountEventsWithAppServiceID(ctx, ws.AppService.ID)
if err != nil {
Expand Down Expand Up @@ -206,7 +200,7 @@ func createTransaction(
// send sends events to an application service. Returns an error if an OK was not
// received back from the application service or the request timed out.
func send(
client *http.Client,
client *gomatrixserverlib.Client,
appservice config.ApplicationService,
txnID int,
transaction []byte,
Expand All @@ -219,7 +213,7 @@ func send(
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
resp, err := client.DoHTTPRequest(context.TODO(), req)
if err != nil {
return err
}
Expand Down
30 changes: 22 additions & 8 deletions clientapi/routing/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import (
"github.com/matrix-org/gomatrixserverlib/tokens"
"github.com/matrix-org/util"
"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
log "github.com/sirupsen/logrus"
)

Expand Down Expand Up @@ -496,11 +497,20 @@ func Register(
r.Username = strconv.FormatInt(id, 10)
}

// Is this an appservice registration? It will be if the access
// token is supplied
accessToken, accessTokenErr := auth.ExtractAccessToken(req)

// Squash username to all lowercase letters
r.Username = strings.ToLower(r.Username)

if resErr = validateUsername(r.Username); resErr != nil {
return *resErr
if r.Auth.Type == authtypes.LoginTypeApplicationService || accessTokenErr == nil {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd prefer it if we only look at the access token if the login type is set to AS?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It turns out that this isn't always the case. It's another one of those "spec is vague" things but Synapse also treats all calls to /register with an access_token as if they are coming from an AS.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Decided with @Half-Shot to instead enforce authtypes.LoginTypeApplicationService only.

if resErr = validateApplicationServiceUsername(r.Username); resErr != nil {
return *resErr
}
} else {
if resErr = validateUsername(r.Username); resErr != nil {
return *resErr
}
}
if resErr = validatePassword(r.Password); resErr != nil {
return *resErr
Expand All @@ -513,7 +523,7 @@ func Register(
"session_id": r.Auth.Session,
}).Info("Processing registration request")

return handleRegistrationFlow(req, r, sessionID, cfg, userAPI)
return handleRegistrationFlow(req, r, sessionID, cfg, userAPI, accessToken, accessTokenErr)
}

func handleGuestRegistration(
Expand Down Expand Up @@ -579,6 +589,8 @@ func handleRegistrationFlow(
sessionID string,
cfg *config.ClientAPI,
userAPI userapi.UserInternalAPI,
accessToken string,
accessTokenErr error,
) util.JSONResponse {
// TODO: Shared secret registration (create new user scripts)
// TODO: Enable registration config flag
Expand All @@ -588,12 +600,12 @@ func handleRegistrationFlow(
// TODO: Handle mapping registrationRequest parameters into session parameters

// TODO: email / msisdn auth types.
accessToken, accessTokenErr := auth.ExtractAccessToken(req)

// Appservices are special and are not affected by disabled
// registration or user exclusivity.
if r.Auth.Type == authtypes.LoginTypeApplicationService ||
(r.Auth.Type == "" && accessTokenErr == nil) {
// registration or user exclusivity. We'll go onto the appservice
// registration flow if a valid access token was provided or if
// the login type specifically requests it.
if r.Auth.Type == authtypes.LoginTypeApplicationService || accessTokenErr == nil {
return handleApplicationServiceRegistration(
accessToken, accessTokenErr, req, r, cfg, userAPI,
)
Expand Down Expand Up @@ -679,6 +691,8 @@ func handleApplicationServiceRegistration(
cfg *config.ClientAPI,
userAPI userapi.UserInternalAPI,
) util.JSONResponse {
logrus.Warnf("APPSERVICE Is appservice registration %q", r.Username)
neilalexander marked this conversation as resolved.
Show resolved Hide resolved

// Check if we previously had issues extracting the access token from the
// request.
if tokenErr != nil {
Expand Down
1 change: 1 addition & 0 deletions cmd/generate-config/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ func main() {
}

if *defaultsForCI {
cfg.AppServiceAPI.DisableTLSValidation = true
cfg.ClientAPI.RateLimiting.Enabled = false
cfg.FederationSender.DisableTLSValidation = true
cfg.MSCs.MSCs = []string{"msc2836", "msc2946", "msc2444", "msc2753"}
Expand Down
5 changes: 5 additions & 0 deletions dendrite-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,11 @@ app_service_api:
max_idle_conns: 2
conn_max_lifetime: -1

# Disable the validation of TLS certificates of appservices. This is
# not recommended in production since it may allow appservice traffic
# to be sent to an unverified endpoint.
disable_tls_validation: false

# Appservice configuration files to load into this homeserver.
config_files: []

Expand Down
15 changes: 15 additions & 0 deletions setup/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,21 @@ func (b *BaseDendrite) CreateClient() *gomatrixserverlib.Client {
return client
}

// CreateClient creates a new client (normally used for media fetch requests).
// Should only be called once per component.
func (b *BaseDendrite) CreateAppserviceClient() *gomatrixserverlib.Client {
neilalexander marked this conversation as resolved.
Show resolved Hide resolved
opts := []gomatrixserverlib.ClientOption{
gomatrixserverlib.WithSkipVerify(b.Cfg.AppServiceAPI.DisableTLSValidation),
gomatrixserverlib.WithTimeout(time.Second * 60),
}
if b.Cfg.Global.DNSCache.Enabled {
opts = append(opts, gomatrixserverlib.WithDNSCache(b.DNSCache))
}
client := gomatrixserverlib.NewClient(opts...)
client.SetUserAgent(fmt.Sprintf("Dendrite/%s", internal.VersionString()))
return client
}

// CreateFederationClient creates a new federation client. Should only be called
// once per component.
func (b *BaseDendrite) CreateFederationClient() *gomatrixserverlib.FederationClient {
Expand Down
4 changes: 4 additions & 0 deletions setup/config/config_appservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ type AppServiceAPI struct {

Database DatabaseOptions `yaml:"database"`

// DisableTLSValidation disables the validation of X.509 TLS certs
// on appservice endpoints. This is not recommended in production!
DisableTLSValidation bool `yaml:"disable_tls_validation"`

ConfigFiles []string `yaml:"config_files"`
}

Expand Down
6 changes: 6 additions & 0 deletions sytest-whitelist
Original file line number Diff line number Diff line change
Expand Up @@ -510,3 +510,9 @@ Can pass a JSON filter as a query parameter
Local room members can get room messages
Remote room members can get room messages
Guest users can send messages to guest_access rooms if joined
AS can create a user
AS can create a user with an underscore
AS can create a user with inhibit_login
AS can set avatar for ghosted users
AS can set displayname for ghosted users
Ghost user must register before joining room