2019-01-24 16:26:36 +00:00
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package consoleweb
import (
"context"
2020-01-14 13:38:32 +00:00
"crypto/subtle"
2019-01-24 16:26:36 +00:00
"encoding/json"
2020-04-16 16:50:22 +01:00
"errors"
2020-04-13 10:31:17 +01:00
"fmt"
2019-04-10 00:14:19 +01:00
"html/template"
2019-08-08 13:12:39 +01:00
"mime"
2019-01-24 16:26:36 +00:00
"net"
"net/http"
2019-08-08 13:12:39 +01:00
"net/url"
2019-11-12 13:05:35 +00:00
"os"
2019-01-24 16:26:36 +00:00
"path/filepath"
2019-03-19 17:55:43 +00:00
"strconv"
2019-03-26 15:56:16 +00:00
"strings"
2019-04-10 00:14:19 +01:00
"time"
2019-01-24 16:26:36 +00:00
2019-10-21 17:42:49 +01:00
"github.com/gorilla/mux"
2019-01-24 16:26:36 +00:00
"github.com/graphql-go/graphql"
2020-01-20 13:02:44 +00:00
"github.com/graphql-go/graphql/gqlerrors"
2020-10-09 14:40:12 +01:00
"github.com/spacemonkeygo/monkit/v3"
2019-01-24 16:26:36 +00:00
"github.com/zeebo/errs"
"go.uber.org/zap"
2019-02-06 13:19:14 +00:00
"golang.org/x/sync/errgroup"
2019-01-24 16:26:36 +00:00
2020-04-16 16:50:22 +01:00
"storj.io/common/errs2"
2021-09-22 21:10:15 +01:00
"storj.io/common/memory"
2020-12-23 04:24:37 +00:00
"storj.io/common/storj"
2020-03-30 10:08:50 +01:00
"storj.io/common/uuid"
2020-04-08 20:40:49 +01:00
"storj.io/storj/private/web"
2021-03-23 15:52:34 +00:00
"storj.io/storj/satellite/analytics"
2019-01-24 16:26:36 +00:00
"storj.io/storj/satellite/console"
2020-10-06 11:40:31 +01:00
"storj.io/storj/satellite/console/consoleauth"
2019-10-17 15:42:18 +01:00
"storj.io/storj/satellite/console/consoleweb/consoleapi"
2019-01-24 16:26:36 +00:00
"storj.io/storj/satellite/console/consoleweb/consoleql"
2020-01-20 18:57:14 +00:00
"storj.io/storj/satellite/console/consoleweb/consolewebauth"
2019-03-02 15:22:20 +00:00
"storj.io/storj/satellite/mailservice"
2022-02-03 20:49:38 +00:00
"storj.io/storj/satellite/oidc"
2021-04-15 18:53:09 +01:00
"storj.io/storj/satellite/payments/paymentsconfig"
2020-07-28 15:23:17 +01:00
"storj.io/storj/satellite/rewards"
2019-01-24 16:26:36 +00:00
)
const (
2020-01-20 18:57:14 +00:00
contentType = "Content-Type"
2019-01-24 16:26:36 +00:00
applicationJSON = "application/json"
applicationGraphql = "application/graphql"
)
2019-06-04 12:55:38 +01:00
var (
2020-08-11 15:50:01 +01:00
// Error is satellite console error type.
2021-04-28 09:06:17 +01:00
Error = errs . Class ( "consoleweb" )
2019-06-04 12:55:38 +01:00
mon = monkit . Package ( )
)
2019-01-24 16:26:36 +00:00
2020-07-16 15:18:02 +01:00
// Config contains configuration for console web server.
2019-01-24 16:26:36 +00:00
type Config struct {
testplanet/satellite: reduce the number of places default values need to be configured
Satellites set their configuration values to default values using
cfgstruct, however, it turns out our tests don't test these values
at all! Instead, they have a completely separate definition system
that is easy to forget about.
As is to be expected, these values have drifted, and it appears
in a few cases test planet is testing unreasonable values that we
won't see in production, or perhaps worse, features enabled in
production were missed and weren't enabled in testplanet.
This change makes it so all values are configured the same,
systematic way, so it's easy to see when test values are different
than dev values or release values, and it's less hard to forget
to enable features in testplanet.
In terms of reviewing, this change should be actually fairly
easy to review, considering private/testplanet/satellite.go keeps
the current config system and the new one and confirms that they
result in identical configurations, so you can be certain that
nothing was missed and the config is all correct.
You can also check the config lock to see what actual config
values changed.
Change-Id: I6715d0794887f577e21742afcf56fd2b9d12170e
2021-05-31 22:15:00 +01:00
Address string ` help:"server address of the graphql api gateway and frontend app" devDefault:"127.0.0.1:0" releaseDefault:":10100" `
2019-03-26 15:56:16 +00:00
StaticDir string ` help:"path to static resources" default:"" `
2021-11-03 15:36:20 +00:00
Watch bool ` help:"whether to load templates on each request" default:"false" devDefault:"true" `
2019-03-26 15:56:16 +00:00
ExternalAddress string ` help:"external endpoint of the satellite if hosted" default:"" `
2019-02-05 17:31:53 +00:00
2019-03-19 17:55:43 +00:00
// TODO: remove after Vanguard release
testplanet/satellite: reduce the number of places default values need to be configured
Satellites set their configuration values to default values using
cfgstruct, however, it turns out our tests don't test these values
at all! Instead, they have a completely separate definition system
that is easy to forget about.
As is to be expected, these values have drifted, and it appears
in a few cases test planet is testing unreasonable values that we
won't see in production, or perhaps worse, features enabled in
production were missed and weren't enabled in testplanet.
This change makes it so all values are configured the same,
systematic way, so it's easy to see when test values are different
than dev values or release values, and it's less hard to forget
to enable features in testplanet.
In terms of reviewing, this change should be actually fairly
easy to review, considering private/testplanet/satellite.go keeps
the current config system and the new one and confirms that they
result in identical configurations, so you can be certain that
nothing was missed and the config is all correct.
You can also check the config lock to see what actual config
values changed.
Change-Id: I6715d0794887f577e21742afcf56fd2b9d12170e
2021-05-31 22:15:00 +01:00
AuthToken string ` help:"auth token needed for access to registration token creation endpoint" default:"" testDefault:"very-secret-token" `
2019-05-28 15:32:51 +01:00
AuthTokenSecret string ` help:"secret used to sign auth tokens" releaseDefault:"" devDefault:"my-suppa-secret-key" `
2019-03-19 17:55:43 +00:00
2021-04-23 15:22:20 +01:00
ContactInfoURL string ` help:"url link to contacts page" default:"https://forum.storj.io" `
FrameAncestors string ` help:"allow domains to embed the satellite in a frame, space separated" default:"tardigrade.io storj.io" `
LetUsKnowURL string ` help:"url link to let us know page" default:"https://storjlabs.atlassian.net/servicedesk/customer/portals" `
SEO string ` help:"used to communicate with web crawlers and other web robots" default:"User-agent: *\nDisallow: \nDisallow: /cgi-bin/" `
SatelliteName string ` help:"used to display at web satellite console" default:"Storj" `
SatelliteOperator string ` help:"name of organization which set up satellite" default:"Storj Labs" `
TermsAndConditionsURL string ` help:"url link to terms and conditions page" default:"https://storj.io/storage-sla/" `
AccountActivationRedirectURL string ` help:"url link for account activation redirect" default:"" `
PartneredSatellites SatList ` help:"names and addresses of partnered satellites in JSON list format" default:"[[\"US1\",\"https://us1.storj.io\"],[\"EU1\",\"https://eu1.storj.io\"],[\"AP1\",\"https://ap1.storj.io\"]]" `
GeneralRequestURL string ` help:"url link to general request page" default:"https://supportdcs.storj.io/hc/en-us/requests/new?ticket_form_id=360000379291" `
ProjectLimitsIncreaseRequestURL string ` help:"url link to project limit increase request page" default:"https://supportdcs.storj.io/hc/en-us/requests/new?ticket_form_id=360000683212" `
2022-05-16 17:04:25 +01:00
GatewayCredentialsRequestURL string ` help:"url link for gateway credentials requests" default:"https://auth.storjshare.io" devDefault:"" `
2021-04-23 15:22:20 +01:00
IsBetaSatellite bool ` help:"indicates if satellite is in beta" default:"false" `
BetaSatelliteFeedbackURL string ` help:"url link for for beta satellite feedback" default:"" `
BetaSatelliteSupportURL string ` help:"url link for for beta satellite support" default:"" `
DocumentationURL string ` help:"url link to documentation" default:"https://docs.storj.io/" `
2021-06-22 01:09:56 +01:00
CouponCodeBillingUIEnabled bool ` help:"indicates if user is allowed to add coupon codes to account from billing" default:"false" `
CouponCodeSignupUIEnabled bool ` help:"indicates if user is allowed to add coupon codes to account from signup" default:"false" `
2021-04-23 15:22:20 +01:00
FileBrowserFlowDisabled bool ` help:"indicates if file browser flow is disabled" default:"false" `
CSPEnabled bool ` help:"indicates if Content Security Policy is enabled" devDefault:"false" releaseDefault:"true" `
2022-05-16 17:04:25 +01:00
LinksharingURL string ` help:"url link for linksharing requests" default:"https://link.storjshare.io" devDefault:"" `
2021-04-23 15:22:20 +01:00
PathwayOverviewEnabled bool ` help:"indicates if the overview onboarding step should render with pathways" default:"true" `
2021-11-03 12:16:18 +00:00
NewProjectDashboard bool ` help:"indicates if new project dashboard should be used" default:"false" `
2021-11-16 09:38:42 +00:00
NewNavigation bool ` help:"indicates if new navigation structure should be rendered" default:"true" `
2022-04-22 19:30:56 +01:00
NewObjectsFlow bool ` help:"indicates if new objects flow should be used" default:"false" `
2022-04-29 16:31:52 +01:00
NewAccessGrantFlow bool ` help:"indicates if new access grant flow should be used" default:"false" `
2022-02-11 15:06:52 +00:00
GeneratedAPIEnabled bool ` help:"indicates if generated console api should be used" default:"false" `
2022-01-30 13:49:21 +00:00
InactivityTimerEnabled bool ` help:"indicates if session can be timed out due inactivity" default:"false" `
InactivityTimerDelay int ` help:"inactivity timer delay in seconds" default:"600" `
2022-02-22 19:53:41 +00:00
OptionalSignupSuccessURL string ` help:"optional url to external registration success page" default:"" `
2022-04-22 20:06:47 +01:00
HomepageURL string ` help:"url link to storj.io homepage" default:"https://www.storj.io" `
2020-03-11 15:36:55 +00:00
2022-02-03 20:49:38 +00:00
OauthCodeExpiry time . Duration ` help:"how long oauth authorization codes are issued for" default:"10m" `
OauthAccessTokenExpiry time . Duration ` help:"how long oauth access tokens are issued for" default:"24h" `
OauthRefreshTokenExpiry time . Duration ` help:"how long oauth refresh tokens are issued for" default:"720h" `
2021-08-17 20:38:34 +01:00
// RateLimit defines the configuration for the IP and userID rate limiters.
RateLimit web . RateLimiterConfig
2020-04-08 20:40:49 +01:00
2020-03-11 15:36:55 +00:00
console . Config
2019-01-24 16:26:36 +00:00
}
2021-04-23 15:22:20 +01:00
// SatList is a configuration value that contains a list of satellite names and addresses.
// Format should be [[name,address],[name,address],...] in valid JSON format.
//
// Can be used as a flag.
type SatList string
// Type implements pflag.Value.
func ( SatList ) Type ( ) string { return "consoleweb.SatList" }
// String is required for pflag.Value.
func ( sl * SatList ) String ( ) string {
return string ( * sl )
}
// Set does validation on the configured JSON, but does not actually transform it - it will be passed to the client as-is.
func ( sl * SatList ) Set ( s string ) error {
satellites := make ( [ ] [ ] string , 3 )
err := json . Unmarshal ( [ ] byte ( s ) , & satellites )
if err != nil {
return err
}
for _ , sat := range satellites {
if len ( sat ) != 2 {
return errs . New ( "Could not parse satellite list config. Each satellite in the config must have two values: [name, address]" )
}
}
* sl = SatList ( s )
return nil
}
2020-12-05 16:01:42 +00:00
// Server represents console web server.
2019-09-10 14:24:16 +01:00
//
// architecture: Endpoint
2019-01-24 16:26:36 +00:00
type Server struct {
log * zap . Logger
2021-02-04 18:16:49 +00:00
config Config
service * console . Service
mailService * mailservice . Service
partners * rewards . PartnersService
2021-03-23 15:52:34 +00:00
analytics * analytics . Service
2019-03-02 15:22:20 +00:00
2021-08-17 20:38:34 +01:00
listener net . Listener
server http . Server
cookieAuth * consolewebauth . CookieAuth
ipRateLimiter * web . RateLimiter
userIDRateLimiter * web . RateLimiter
nodeURL storj . NodeURL
2019-01-24 16:26:36 +00:00
2019-11-18 11:38:43 +00:00
stripePublicKey string
2021-04-15 18:53:09 +01:00
pricing paymentsconfig . PricingValues
2021-11-03 15:36:20 +00:00
schema graphql . Schema
templatesCache * templates
}
type templates struct {
index * template . Template
notFound * template . Template
internalServerError * template . Template
usageReport * template . Template
2019-01-24 16:26:36 +00:00
}
2019-10-17 15:42:18 +01:00
// NewServer creates new instance of console server.
2022-02-03 20:49:38 +00:00
func NewServer ( logger * zap . Logger , config Config , service * console . Service , oidcService * oidc . Service , mailService * mailservice . Service , partners * rewards . PartnersService , analytics * analytics . Service , listener net . Listener , stripePublicKey string , pricing paymentsconfig . PricingValues , nodeURL storj . NodeURL ) * Server {
2019-01-24 16:26:36 +00:00
server := Server {
2021-08-17 20:38:34 +01:00
log : logger ,
config : config ,
listener : listener ,
service : service ,
mailService : mailService ,
partners : partners ,
analytics : analytics ,
stripePublicKey : stripePublicKey ,
ipRateLimiter : web . NewIPRateLimiter ( config . RateLimit ) ,
userIDRateLimiter : NewUserIDRateLimiter ( config . RateLimit ) ,
nodeURL : nodeURL ,
pricing : pricing ,
2019-01-24 16:26:36 +00:00
}
2020-04-13 10:31:17 +01:00
logger . Debug ( "Starting Satellite UI." , zap . Stringer ( "Address" , server . listener . Addr ( ) ) )
2019-02-28 20:12:52 +00:00
2020-01-20 18:57:14 +00:00
server . cookieAuth = consolewebauth . NewCookieAuth ( consolewebauth . CookieSettings {
Name : "_tokenKey" ,
Path : "/" ,
} )
2019-03-26 15:56:16 +00:00
if server . config . ExternalAddress != "" {
if ! strings . HasSuffix ( server . config . ExternalAddress , "/" ) {
2019-05-29 14:14:25 +01:00
server . config . ExternalAddress += "/"
2019-03-26 15:56:16 +00:00
}
} else {
server . config . ExternalAddress = "http://" + server . listener . Addr ( ) . String ( ) + "/"
}
2020-03-23 20:38:50 +00:00
if server . config . AccountActivationRedirectURL == "" {
server . config . AccountActivationRedirectURL = server . config . ExternalAddress + "login?activated=true"
}
2019-10-21 17:42:49 +01:00
router := mux . NewRouter ( )
2019-10-22 17:17:09 +01:00
2022-02-17 13:49:07 +00:00
if server . config . GeneratedAPIEnabled {
consoleapi . NewProjectManagement ( logger , server . service , router , server . service )
}
2019-10-21 17:42:49 +01:00
router . HandleFunc ( "/registrationToken/" , server . createRegistrationTokenHandler )
router . HandleFunc ( "/robots.txt" , server . seoHandler )
2020-10-21 10:58:37 +01:00
router . Handle ( "/api/v0/graphql" , server . withAuth ( http . HandlerFunc ( server . graphqlHandler ) ) )
2020-01-20 18:57:14 +00:00
2021-06-24 16:49:15 +01:00
usageLimitsController := consoleapi . NewUsageLimits ( logger , service )
2019-12-12 12:58:15 +00:00
router . Handle (
"/api/v0/projects/{id}/usage-limits" ,
2021-06-24 16:49:15 +01:00
server . withAuth ( http . HandlerFunc ( usageLimitsController . ProjectUsageLimits ) ) ,
) . Methods ( http . MethodGet )
router . Handle (
"/api/v0/projects/usage-limits" ,
server . withAuth ( http . HandlerFunc ( usageLimitsController . TotalUsageLimits ) ) ,
2019-12-12 12:58:15 +00:00
) . Methods ( http . MethodGet )
2021-12-07 14:41:39 +00:00
router . Handle (
"/api/v0/projects/{id}/daily-usage" ,
server . withAuth ( http . HandlerFunc ( usageLimitsController . DailyUsage ) ) ,
) . Methods ( http . MethodGet )
2019-12-12 12:58:15 +00:00
2021-03-23 15:52:34 +00:00
authController := consoleapi . NewAuth ( logger , service , mailService , server . cookieAuth , partners , server . analytics , server . config . ExternalAddress , config . LetUsKnowURL , config . TermsAndConditionsURL , config . ContactInfoURL )
2019-10-23 18:33:24 +01:00
authRouter := router . PathPrefix ( "/api/v0/auth" ) . Subrouter ( )
2019-10-29 14:24:16 +00:00
authRouter . Handle ( "/account" , server . withAuth ( http . HandlerFunc ( authController . GetAccount ) ) ) . Methods ( http . MethodGet )
authRouter . Handle ( "/account" , server . withAuth ( http . HandlerFunc ( authController . UpdateAccount ) ) ) . Methods ( http . MethodPatch )
2020-11-05 16:16:55 +00:00
authRouter . Handle ( "/account/change-email" , server . withAuth ( http . HandlerFunc ( authController . ChangeEmail ) ) ) . Methods ( http . MethodPost )
2019-10-29 14:24:16 +00:00
authRouter . Handle ( "/account/change-password" , server . withAuth ( http . HandlerFunc ( authController . ChangePassword ) ) ) . Methods ( http . MethodPost )
authRouter . Handle ( "/account/delete" , server . withAuth ( http . HandlerFunc ( authController . DeleteAccount ) ) ) . Methods ( http . MethodPost )
2021-07-13 18:21:16 +01:00
authRouter . Handle ( "/mfa/enable" , server . withAuth ( http . HandlerFunc ( authController . EnableUserMFA ) ) ) . Methods ( http . MethodPost )
authRouter . Handle ( "/mfa/disable" , server . withAuth ( http . HandlerFunc ( authController . DisableUserMFA ) ) ) . Methods ( http . MethodPost )
authRouter . Handle ( "/mfa/generate-secret-key" , server . withAuth ( http . HandlerFunc ( authController . GenerateMFASecretKey ) ) ) . Methods ( http . MethodPost )
authRouter . Handle ( "/mfa/generate-recovery-codes" , server . withAuth ( http . HandlerFunc ( authController . GenerateMFARecoveryCodes ) ) ) . Methods ( http . MethodPost )
2020-02-21 11:47:53 +00:00
authRouter . HandleFunc ( "/logout" , authController . Logout ) . Methods ( http . MethodPost )
2021-08-17 20:38:34 +01:00
authRouter . Handle ( "/token" , server . ipRateLimiter . Limit ( http . HandlerFunc ( authController . Token ) ) ) . Methods ( http . MethodPost )
authRouter . Handle ( "/register" , server . ipRateLimiter . Limit ( http . HandlerFunc ( authController . Register ) ) ) . Methods ( http . MethodPost , http . MethodOptions )
authRouter . Handle ( "/forgot-password/{email}" , server . ipRateLimiter . Limit ( http . HandlerFunc ( authController . ForgotPassword ) ) ) . Methods ( http . MethodPost )
2021-11-18 18:55:37 +00:00
authRouter . Handle ( "/resend-email/{email}" , server . ipRateLimiter . Limit ( http . HandlerFunc ( authController . ResendEmail ) ) ) . Methods ( http . MethodPost )
2021-08-17 20:38:34 +01:00
authRouter . Handle ( "/reset-password" , server . ipRateLimiter . Limit ( http . HandlerFunc ( authController . ResetPassword ) ) ) . Methods ( http . MethodPost )
2019-10-21 13:48:29 +01:00
2019-10-23 18:33:24 +01:00
paymentController := consoleapi . NewPayments ( logger , service )
paymentsRouter := router . PathPrefix ( "/api/v0/payments" ) . Subrouter ( )
paymentsRouter . Use ( server . withAuth )
paymentsRouter . HandleFunc ( "/cards" , paymentController . AddCreditCard ) . Methods ( http . MethodPost )
paymentsRouter . HandleFunc ( "/cards" , paymentController . MakeCreditCardDefault ) . Methods ( http . MethodPatch )
paymentsRouter . HandleFunc ( "/cards" , paymentController . ListCreditCards ) . Methods ( http . MethodGet )
paymentsRouter . HandleFunc ( "/cards/{cardId}" , paymentController . RemoveCreditCard ) . Methods ( http . MethodDelete )
2019-11-15 14:27:44 +00:00
paymentsRouter . HandleFunc ( "/account/charges" , paymentController . ProjectsCharges ) . Methods ( http . MethodGet )
2019-10-23 18:33:24 +01:00
paymentsRouter . HandleFunc ( "/account/balance" , paymentController . AccountBalance ) . Methods ( http . MethodGet )
paymentsRouter . HandleFunc ( "/account" , paymentController . SetupAccount ) . Methods ( http . MethodPost )
2022-05-11 09:02:58 +01:00
paymentsRouter . HandleFunc ( "/wallet" , paymentController . GetWallet ) . Methods ( http . MethodGet )
paymentsRouter . HandleFunc ( "/wallet" , paymentController . ClaimWallet ) . Methods ( http . MethodPost )
paymentsRouter . HandleFunc ( "/transactions" , paymentController . Transactions ) . Methods ( http . MethodGet )
2019-10-31 16:56:54 +00:00
paymentsRouter . HandleFunc ( "/billing-history" , paymentController . BillingHistory ) . Methods ( http . MethodGet )
2019-11-12 11:14:34 +00:00
paymentsRouter . HandleFunc ( "/tokens/deposit" , paymentController . TokenDeposit ) . Methods ( http . MethodPost )
2021-08-17 20:38:34 +01:00
paymentsRouter . Handle ( "/coupon/apply" , server . userIDRateLimiter . Limit ( http . HandlerFunc ( paymentController . ApplyCouponCode ) ) ) . Methods ( http . MethodPatch )
2021-08-06 21:14:33 +01:00
paymentsRouter . HandleFunc ( "/coupon" , paymentController . GetCoupon ) . Methods ( http . MethodGet )
2019-01-24 16:26:36 +00:00
2020-11-13 11:41:35 +00:00
bucketsController := consoleapi . NewBuckets ( logger , service )
bucketsRouter := router . PathPrefix ( "/api/v0/buckets" ) . Subrouter ( )
bucketsRouter . Use ( server . withAuth )
bucketsRouter . HandleFunc ( "/bucket-names" , bucketsController . AllBucketNames ) . Methods ( http . MethodGet )
2021-03-16 19:43:02 +00:00
apiKeysController := consoleapi . NewAPIKeys ( logger , service )
apiKeysRouter := router . PathPrefix ( "/api/v0/api-keys" ) . Subrouter ( )
apiKeysRouter . Use ( server . withAuth )
apiKeysRouter . HandleFunc ( "/delete-by-name" , apiKeysController . DeleteByNameAndProjectID ) . Methods ( http . MethodDelete )
2021-03-31 19:34:44 +01:00
analyticsController := consoleapi . NewAnalytics ( logger , service , server . analytics )
analyticsRouter := router . PathPrefix ( "/api/v0/analytics" ) . Subrouter ( )
analyticsRouter . Use ( server . withAuth )
analyticsRouter . HandleFunc ( "/event" , analyticsController . EventTriggered ) . Methods ( http . MethodPost )
2019-01-24 16:26:36 +00:00
if server . config . StaticDir != "" {
2022-02-08 21:28:11 +00:00
oidc := oidc . NewEndpoint ( server . config . ExternalAddress , logger , oidcService , service ,
server . config . OauthCodeExpiry , server . config . OauthAccessTokenExpiry , server . config . OauthRefreshTokenExpiry )
2022-02-03 20:49:38 +00:00
router . HandleFunc ( "/.well-known/openid-configuration" , oidc . WellKnownConfiguration )
router . Handle ( "/oauth/v2/authorize" , server . withAuth ( http . HandlerFunc ( oidc . AuthorizeUser ) ) ) . Methods ( http . MethodPost )
router . Handle ( "/oauth/v2/tokens" , server . ipRateLimiter . Limit ( http . HandlerFunc ( oidc . Tokens ) ) ) . Methods ( http . MethodPost )
router . Handle ( "/oauth/v2/userinfo" , server . ipRateLimiter . Limit ( http . HandlerFunc ( oidc . UserInfo ) ) ) . Methods ( http . MethodGet )
2022-02-14 20:06:35 +00:00
router . Handle ( "/oauth/v2/clients/{id}" , server . withAuth ( http . HandlerFunc ( oidc . GetClient ) ) ) . Methods ( http . MethodGet )
2022-02-03 20:49:38 +00:00
fs := http . FileServer ( http . Dir ( server . config . StaticDir ) )
router . PathPrefix ( "/static/" ) . Handler ( server . brotliMiddleware ( http . StripPrefix ( "/static" , fs ) ) )
2019-10-21 17:42:49 +01:00
router . HandleFunc ( "/activation/" , server . accountActivationHandler )
router . HandleFunc ( "/cancel-password-recovery/" , server . cancelPasswordRecoveryHandler )
2019-11-22 17:03:15 +00:00
router . HandleFunc ( "/usage-report" , server . bucketUsageReportHandler )
2019-10-21 17:42:49 +01:00
router . PathPrefix ( "/" ) . Handler ( http . HandlerFunc ( server . appHandler ) )
2019-01-24 16:26:36 +00:00
}
server . server = http . Server {
2020-09-06 02:56:07 +01:00
Handler : server . withRequest ( router ) ,
2019-09-20 18:40:26 +01:00
MaxHeaderBytes : ContentLengthLimit . Int ( ) ,
2019-01-24 16:26:36 +00:00
}
return & server
}
2020-01-24 13:38:53 +00:00
// Run starts the server that host webapp and api endpoint.
2019-08-13 13:37:01 +01:00
func ( server * Server ) Run ( ctx context . Context ) ( err error ) {
defer mon . Task ( ) ( & ctx ) ( & err )
server . schema , err = consoleql . CreateSchema ( server . log , server . service , server . mailService )
if err != nil {
return Error . Wrap ( err )
}
2021-11-03 15:36:20 +00:00
_ , err = server . loadTemplates ( )
2019-08-13 13:37:01 +01:00
if err != nil {
// TODO: should it return error if some template can not be initialized or just log about it?
return Error . Wrap ( err )
}
ctx , cancel := context . WithCancel ( ctx )
var group errgroup . Group
group . Go ( func ( ) error {
<- ctx . Done ( )
2019-08-22 12:40:15 +01:00
return server . server . Shutdown ( context . Background ( ) )
2019-08-13 13:37:01 +01:00
} )
group . Go ( func ( ) error {
2021-08-17 20:38:34 +01:00
server . ipRateLimiter . Run ( ctx )
2020-04-08 20:40:49 +01:00
return nil
} )
group . Go ( func ( ) error {
2019-08-13 13:37:01 +01:00
defer cancel ( )
2020-04-16 16:50:22 +01:00
err := server . server . Serve ( server . listener )
if errs2 . IsCanceled ( err ) || errors . Is ( err , http . ErrServerClosed ) {
err = nil
}
return err
2019-08-13 13:37:01 +01:00
} )
return group . Wait ( )
}
2020-07-16 15:18:02 +01:00
// Close closes server and underlying listener.
2019-08-13 13:37:01 +01:00
func ( server * Server ) Close ( ) error {
return server . server . Close ( )
}
2020-07-16 15:18:02 +01:00
// appHandler is web app http handler function.
2019-08-13 13:37:01 +01:00
func ( server * Server ) appHandler ( w http . ResponseWriter , r * http . Request ) {
2019-07-30 11:13:24 +01:00
header := w . Header ( )
2021-04-09 12:37:33 +01:00
if server . config . CSPEnabled {
cspValues := [ ] string {
"default-src 'self'" ,
2022-05-06 21:56:18 +01:00
"connect-src 'self' *.tardigradeshare.io *.storjshare.io https://hcaptcha.com, https://*.hcaptcha.com " + server . config . GatewayCredentialsRequestURL ,
2021-04-09 12:37:33 +01:00
"frame-ancestors " + server . config . FrameAncestors ,
2022-05-06 21:56:18 +01:00
"frame-src 'self' *.stripe.com https://www.google.com/recaptcha/ https://recaptcha.google.com/recaptcha/ https://hcaptcha.com https://*.hcaptcha.com" ,
2022-02-23 22:10:18 +00:00
"img-src 'self' data: blob: *.tardigradeshare.io *.storjshare.io" ,
2021-12-09 15:05:21 +00:00
// Those are hashes of charts custom tooltip inline styles. They have to be updated if styles are updated.
2022-05-06 21:56:18 +01:00
"style-src 'unsafe-hashes' 'sha256-7mY2NKmZ4PuyjGUa4FYC5u36SxXdoUM/zxrlr3BEToo=' 'sha256-PRTMwLUW5ce9tdiUrVCGKqj6wPeuOwGogb1pmyuXhgI=' 'sha256-kwpt3lQZ21rs4cld7/uEm9qI5yAbjYzx+9FGm/XmwNU=' 'self' https://hcaptcha.com, https://*.hcaptcha.com" ,
2022-02-23 22:10:18 +00:00
"media-src 'self' blob: *.tardigradeshare.io *.storjshare.io" ,
2022-05-06 21:56:18 +01:00
"script-src 'sha256-wAqYV6m2PHGd1WDyFBnZmSoyfCK0jxFAns0vGbdiWUA=' 'self' *.stripe.com https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/ https://hcaptcha.com https://*.hcaptcha.com" ,
2021-04-09 12:37:33 +01:00
}
header . Set ( "Content-Security-Policy" , strings . Join ( cspValues , "; " ) )
2019-07-30 11:13:24 +01:00
}
2019-09-09 19:33:05 +01:00
header . Set ( contentType , "text/html; charset=UTF-8" )
header . Set ( "X-Content-Type-Options" , "nosniff" )
2019-11-21 16:15:22 +00:00
header . Set ( "Referrer-Policy" , "same-origin" ) // Only expose the referring url when navigating around the satellite itself.
2019-07-30 11:13:24 +01:00
2019-11-06 12:27:26 +00:00
var data struct {
2021-02-08 13:06:44 +00:00
ExternalAddress string
2020-09-04 14:58:50 +01:00
SatelliteName string
2020-12-23 04:24:37 +00:00
SatelliteNodeURL string
2020-09-04 14:58:50 +01:00
StripePublicKey string
2021-04-23 15:22:20 +01:00
PartneredSatellites string
2020-09-04 14:58:50 +01:00
DefaultProjectLimit int
GeneralRequestURL string
ProjectLimitsIncreaseRequestURL string
2020-11-24 22:29:19 +00:00
GatewayCredentialsRequestURL string
2021-02-23 17:26:24 +00:00
IsBetaSatellite bool
2021-03-11 15:05:06 +00:00
BetaSatelliteFeedbackURL string
BetaSatelliteSupportURL string
2021-02-25 01:05:45 +00:00
DocumentationURL string
2021-06-22 01:09:56 +01:00
CouponCodeBillingUIEnabled bool
CouponCodeSignupUIEnabled bool
2021-03-23 20:50:34 +00:00
FileBrowserFlowDisabled bool
2021-04-09 12:56:21 +01:00
LinksharingURL string
2021-04-09 15:43:10 +01:00
PathwayOverviewEnabled bool
2021-04-15 18:53:09 +01:00
StorageTBPrice string
EgressTBPrice string
2021-10-20 23:54:34 +01:00
SegmentPrice string
2021-06-25 12:17:55 +01:00
RecaptchaEnabled bool
RecaptchaSiteKey string
2022-05-06 21:56:18 +01:00
HcaptchaEnabled bool
HcaptchaSiteKey string
2021-11-03 12:16:18 +00:00
NewProjectDashboard bool
2021-09-22 21:10:15 +01:00
DefaultPaidStorageLimit memory . Size
DefaultPaidBandwidthLimit memory . Size
2021-10-08 11:58:11 +01:00
NewNavigation bool
2021-11-02 13:36:28 +00:00
NewObjectsFlow bool
2022-04-29 16:31:52 +01:00
NewAccessGrantFlow bool
2022-01-30 13:49:21 +00:00
InactivityTimerEnabled bool
InactivityTimerDelay int
2022-02-22 19:53:41 +00:00
OptionalSignupSuccessURL string
2022-04-22 20:06:47 +01:00
HomepageURL string
2019-11-06 12:27:26 +00:00
}
2021-02-08 13:06:44 +00:00
data . ExternalAddress = server . config . ExternalAddress
2019-11-06 12:27:26 +00:00
data . SatelliteName = server . config . SatelliteName
2020-12-23 04:24:37 +00:00
data . SatelliteNodeURL = server . nodeURL . String ( )
2019-11-18 11:38:43 +00:00
data . StripePublicKey = server . stripePublicKey
2021-04-23 15:22:20 +01:00
data . PartneredSatellites = string ( server . config . PartneredSatellites )
2020-07-15 17:49:37 +01:00
data . DefaultProjectLimit = server . config . DefaultProjectLimit
2020-09-04 14:58:50 +01:00
data . GeneralRequestURL = server . config . GeneralRequestURL
data . ProjectLimitsIncreaseRequestURL = server . config . ProjectLimitsIncreaseRequestURL
2020-11-24 22:29:19 +00:00
data . GatewayCredentialsRequestURL = server . config . GatewayCredentialsRequestURL
2021-02-23 17:26:24 +00:00
data . IsBetaSatellite = server . config . IsBetaSatellite
2021-03-11 15:05:06 +00:00
data . BetaSatelliteFeedbackURL = server . config . BetaSatelliteFeedbackURL
data . BetaSatelliteSupportURL = server . config . BetaSatelliteSupportURL
2021-02-25 01:05:45 +00:00
data . DocumentationURL = server . config . DocumentationURL
2021-06-22 01:09:56 +01:00
data . CouponCodeBillingUIEnabled = server . config . CouponCodeBillingUIEnabled
data . CouponCodeSignupUIEnabled = server . config . CouponCodeSignupUIEnabled
2021-03-23 20:50:34 +00:00
data . FileBrowserFlowDisabled = server . config . FileBrowserFlowDisabled
2021-04-09 12:56:21 +01:00
data . LinksharingURL = server . config . LinksharingURL
2021-04-09 15:43:10 +01:00
data . PathwayOverviewEnabled = server . config . PathwayOverviewEnabled
2021-09-22 21:10:15 +01:00
data . DefaultPaidStorageLimit = server . config . UsageLimits . Storage . Paid
data . DefaultPaidBandwidthLimit = server . config . UsageLimits . Bandwidth . Paid
2021-04-15 18:53:09 +01:00
data . StorageTBPrice = server . pricing . StorageTBPrice
data . EgressTBPrice = server . pricing . EgressTBPrice
2021-10-20 23:54:34 +01:00
data . SegmentPrice = server . pricing . SegmentPrice
2021-06-25 12:17:55 +01:00
data . RecaptchaEnabled = server . config . Recaptcha . Enabled
data . RecaptchaSiteKey = server . config . Recaptcha . SiteKey
2022-05-06 21:56:18 +01:00
data . HcaptchaEnabled = server . config . Hcaptcha . Enabled
data . HcaptchaSiteKey = server . config . Hcaptcha . SiteKey
2021-11-03 12:16:18 +00:00
data . NewProjectDashboard = server . config . NewProjectDashboard
2021-10-08 11:58:11 +01:00
data . NewNavigation = server . config . NewNavigation
2021-11-02 13:36:28 +00:00
data . NewObjectsFlow = server . config . NewObjectsFlow
2022-04-29 16:31:52 +01:00
data . NewAccessGrantFlow = server . config . NewAccessGrantFlow
2022-01-30 13:49:21 +00:00
data . InactivityTimerEnabled = server . config . InactivityTimerEnabled
data . InactivityTimerDelay = server . config . InactivityTimerDelay
2022-02-22 19:53:41 +00:00
data . OptionalSignupSuccessURL = server . config . OptionalSignupSuccessURL
2022-04-22 20:06:47 +01:00
data . HomepageURL = server . config . HomepageURL
2019-11-06 12:27:26 +00:00
2021-11-03 15:36:20 +00:00
templates , err := server . loadTemplates ( )
if err != nil || templates . index == nil {
server . log . Error ( "unable to load templates" , zap . Error ( err ) )
fmt . Fprintf ( w , "Unable to load templates. See whether satellite UI has been built." )
2020-09-16 17:01:09 +01:00
return
}
2021-11-03 15:36:20 +00:00
if err := templates . index . Execute ( w , data ) ; err != nil {
2020-09-16 17:01:09 +01:00
server . log . Error ( "index template could not be executed" , zap . Error ( err ) )
2019-08-13 13:37:01 +01:00
return
}
2019-01-24 16:26:36 +00:00
}
2019-10-21 17:42:49 +01:00
// authMiddlewareHandler performs initial authorization before every request.
func ( server * Server ) withAuth ( handler http . Handler ) http . Handler {
return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
var err error
2020-01-20 18:57:14 +00:00
var ctx context . Context
2019-10-21 17:42:49 +01:00
defer mon . Task ( ) ( & ctx ) ( & err )
2020-01-20 18:57:14 +00:00
ctxWithAuth := func ( ctx context . Context ) context . Context {
token , err := server . cookieAuth . GetToken ( r )
if err != nil {
return console . WithAuthFailure ( ctx , err )
}
2020-10-06 11:40:31 +01:00
ctx = consoleauth . WithAPIKey ( ctx , [ ] byte ( token ) )
2020-01-20 18:57:14 +00:00
auth , err := server . service . Authorize ( ctx )
if err != nil {
return console . WithAuthFailure ( ctx , err )
}
return console . WithAuth ( ctx , auth )
2019-10-21 17:42:49 +01:00
}
2020-01-20 18:57:14 +00:00
ctx = ctxWithAuth ( r . Context ( ) )
2019-10-21 17:42:49 +01:00
handler . ServeHTTP ( w , r . Clone ( ctx ) )
} )
}
2020-09-06 02:56:07 +01:00
// withRequest ensures the http request itself is reachable from the context.
func ( server * Server ) withRequest ( handler http . Handler ) http . Handler {
return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
handler . ServeHTTP ( w , r . Clone ( console . WithRequest ( r . Context ( ) , r ) ) )
} )
}
2020-01-24 13:38:53 +00:00
// bucketUsageReportHandler generate bucket usage report page for project.
2019-08-08 13:12:39 +01:00
func ( server * Server ) bucketUsageReportHandler ( w http . ResponseWriter , r * http . Request ) {
ctx := r . Context ( )
2019-04-10 00:14:19 +01:00
var err error
2019-06-04 12:55:38 +01:00
defer mon . Task ( ) ( & ctx ) ( & err )
2019-04-10 00:14:19 +01:00
2020-01-20 18:57:14 +00:00
token , err := server . cookieAuth . GetToken ( r )
2019-09-13 16:38:29 +01:00
if err != nil {
2019-10-31 18:42:28 +00:00
server . serveError ( w , http . StatusUnauthorized )
2019-04-10 00:14:19 +01:00
return
}
2020-10-06 11:40:31 +01:00
auth , err := server . service . Authorize ( consoleauth . WithAPIKey ( ctx , [ ] byte ( token ) ) )
2019-04-10 00:14:19 +01:00
if err != nil {
2019-10-31 18:42:28 +00:00
server . serveError ( w , http . StatusUnauthorized )
2019-04-10 00:14:19 +01:00
return
}
2019-09-13 16:38:29 +01:00
ctx = console . WithAuth ( ctx , auth )
2019-04-10 00:14:19 +01:00
// parse query params
2020-04-02 13:30:43 +01:00
projectID , err := uuid . FromString ( r . URL . Query ( ) . Get ( "projectID" ) )
2019-04-10 00:14:19 +01:00
if err != nil {
2019-10-31 18:42:28 +00:00
server . serveError ( w , http . StatusBadRequest )
2019-04-10 00:14:19 +01:00
return
}
2019-08-08 13:12:39 +01:00
sinceStamp , err := strconv . ParseInt ( r . URL . Query ( ) . Get ( "since" ) , 10 , 64 )
2019-04-10 00:14:19 +01:00
if err != nil {
2019-10-31 18:42:28 +00:00
server . serveError ( w , http . StatusBadRequest )
2019-04-10 00:14:19 +01:00
return
}
2019-08-08 13:12:39 +01:00
beforeStamp , err := strconv . ParseInt ( r . URL . Query ( ) . Get ( "before" ) , 10 , 64 )
2019-04-10 00:14:19 +01:00
if err != nil {
2019-10-31 18:42:28 +00:00
server . serveError ( w , http . StatusBadRequest )
2019-04-10 00:14:19 +01:00
return
}
2020-01-02 12:52:33 +00:00
since := time . Unix ( sinceStamp , 0 ) . UTC ( )
before := time . Unix ( beforeStamp , 0 ) . UTC ( )
2019-04-23 13:56:15 +01:00
2019-08-08 13:12:39 +01:00
server . log . Debug ( "querying bucket usage report" ,
2019-06-18 00:37:44 +01:00
zap . Stringer ( "projectID" , projectID ) ,
zap . Stringer ( "since" , since ) ,
zap . Stringer ( "before" , before ) )
2019-04-10 00:14:19 +01:00
2020-04-02 13:30:43 +01:00
bucketRollups , err := server . service . GetBucketUsageRollups ( ctx , projectID , since , before )
2019-04-10 00:14:19 +01:00
if err != nil {
2019-09-13 16:38:29 +01:00
server . log . Error ( "bucket usage report error" , zap . Error ( err ) )
2019-10-31 18:42:28 +00:00
server . serveError ( w , http . StatusInternalServerError )
2019-04-10 00:14:19 +01:00
return
}
2021-11-03 15:36:20 +00:00
templates , err := server . loadTemplates ( )
if err != nil {
server . log . Error ( "unable to load templates" , zap . Error ( err ) )
return
}
if err = templates . usageReport . Execute ( w , bucketRollups ) ; err != nil {
2019-09-13 16:38:29 +01:00
server . log . Error ( "bucket usage report error" , zap . Error ( err ) )
2019-04-10 00:14:19 +01:00
}
}
2020-01-18 02:34:06 +00:00
// createRegistrationTokenHandler is web app http handler function.
2019-08-08 13:12:39 +01:00
func ( server * Server ) createRegistrationTokenHandler ( w http . ResponseWriter , r * http . Request ) {
ctx := r . Context ( )
2019-06-04 12:55:38 +01:00
defer mon . Task ( ) ( & ctx ) ( nil )
2019-03-19 17:55:43 +00:00
w . Header ( ) . Set ( contentType , applicationJSON )
var response struct {
Secret string ` json:"secret" `
Error string ` json:"error,omitempty" `
}
defer func ( ) {
err := json . NewEncoder ( w ) . Encode ( & response )
if err != nil {
2019-08-08 13:12:39 +01:00
server . log . Error ( err . Error ( ) )
2019-03-19 17:55:43 +00:00
}
} ( )
2020-01-14 13:38:32 +00:00
equality := subtle . ConstantTimeCompare (
[ ] byte ( r . Header . Get ( "Authorization" ) ) ,
[ ] byte ( server . config . AuthToken ) ,
)
if equality != 1 {
2019-03-19 17:55:43 +00:00
w . WriteHeader ( 401 )
response . Error = "unauthorized"
return
}
2019-08-08 13:12:39 +01:00
projectsLimitInput := r . URL . Query ( ) . Get ( "projectsLimit" )
2019-03-19 17:55:43 +00:00
projectsLimit , err := strconv . Atoi ( projectsLimitInput )
if err != nil {
response . Error = err . Error ( )
return
}
2019-08-08 13:12:39 +01:00
token , err := server . service . CreateRegToken ( ctx , projectsLimit )
2019-03-19 17:55:43 +00:00
if err != nil {
response . Error = err . Error ( )
return
}
response . Secret = token . Secret . String ( )
}
2020-07-16 15:18:02 +01:00
// accountActivationHandler is web app http handler function.
2019-08-08 13:12:39 +01:00
func ( server * Server ) accountActivationHandler ( w http . ResponseWriter , r * http . Request ) {
ctx := r . Context ( )
2019-06-04 12:55:38 +01:00
defer mon . Task ( ) ( & ctx ) ( nil )
2019-08-08 13:12:39 +01:00
activationToken := r . URL . Query ( ) . Get ( "token" )
2019-03-08 14:01:11 +00:00
2021-10-06 14:33:54 +01:00
token , err := server . service . ActivateAccount ( ctx , activationToken )
2019-03-08 14:01:11 +00:00
if err != nil {
2019-08-08 13:12:39 +01:00
server . log . Error ( "activation: failed to activate account" ,
2019-04-09 13:20:29 +01:00
zap . String ( "token" , activationToken ) ,
zap . Error ( err ) )
2020-02-10 12:03:38 +00:00
if console . ErrEmailUsed . Has ( err ) {
2021-07-26 17:11:44 +01:00
http . Redirect ( w , r , server . config . ExternalAddress + "login?activated=false" , http . StatusTemporaryRedirect )
2020-02-10 12:03:38 +00:00
return
}
if console . Error . Has ( err ) {
server . serveError ( w , http . StatusInternalServerError )
return
}
2019-10-31 18:42:28 +00:00
server . serveError ( w , http . StatusNotFound )
2019-03-08 14:01:11 +00:00
return
}
2021-10-06 14:33:54 +01:00
server . cookieAuth . SetTokenCookie ( w , token )
http . Redirect ( w , r , server . config . ExternalAddress , http . StatusTemporaryRedirect )
2019-03-08 14:01:11 +00:00
}
2019-08-08 13:12:39 +01:00
func ( server * Server ) cancelPasswordRecoveryHandler ( w http . ResponseWriter , r * http . Request ) {
ctx := r . Context ( )
2019-06-04 12:55:38 +01:00
defer mon . Task ( ) ( & ctx ) ( nil )
2019-08-08 13:12:39 +01:00
recoveryToken := r . URL . Query ( ) . Get ( "token" )
2019-05-13 16:53:52 +01:00
// No need to check error as we anyway redirect user to support page
2019-08-08 13:12:39 +01:00
_ = server . service . RevokeResetPasswordToken ( ctx , recoveryToken )
2019-05-13 16:53:52 +01:00
2019-08-13 13:37:01 +01:00
// TODO: Should place this link to config
2019-08-08 13:12:39 +01:00
http . Redirect ( w , r , "https://storjlabs.atlassian.net/servicedesk/customer/portals" , http . StatusSeeOther )
2019-05-13 16:53:52 +01:00
}
2020-10-21 10:58:37 +01:00
// graphqlHandler is graphql endpoint http handler function.
func ( server * Server ) graphqlHandler ( w http . ResponseWriter , r * http . Request ) {
2019-08-08 13:12:39 +01:00
ctx := r . Context ( )
2019-06-04 12:55:38 +01:00
defer mon . Task ( ) ( & ctx ) ( nil )
2020-01-20 13:02:44 +00:00
handleError := func ( code int , err error ) {
w . WriteHeader ( code )
var jsonError struct {
Error string ` json:"error" `
}
jsonError . Error = err . Error ( )
if err := json . NewEncoder ( w ) . Encode ( jsonError ) ; err != nil {
server . log . Error ( "error graphql error" , zap . Error ( err ) )
}
}
2019-01-24 16:26:36 +00:00
w . Header ( ) . Set ( contentType , applicationJSON )
2019-09-20 18:40:26 +01:00
query , err := getQuery ( w , r )
2019-01-24 16:26:36 +00:00
if err != nil {
2020-01-20 13:02:44 +00:00
handleError ( http . StatusBadRequest , err )
2019-01-24 16:26:36 +00:00
return
}
2019-03-02 15:22:20 +00:00
rootObject := make ( map [ string ] interface { } )
2019-03-26 15:56:16 +00:00
2019-08-08 13:12:39 +01:00
rootObject [ "origin" ] = server . config . ExternalAddress
2019-03-08 14:01:11 +00:00
rootObject [ consoleql . ActivationPath ] = "activation/?token="
2019-04-10 20:16:10 +01:00
rootObject [ consoleql . PasswordRecoveryPath ] = "password-recovery/?token="
2019-05-13 16:53:52 +01:00
rootObject [ consoleql . CancelPasswordRecoveryPath ] = "cancel-password-recovery/?token="
2019-03-26 15:56:16 +00:00
rootObject [ consoleql . SignInPath ] = "login"
2019-09-27 17:48:53 +01:00
rootObject [ consoleql . LetUsKnowURL ] = server . config . LetUsKnowURL
rootObject [ consoleql . ContactInfoURL ] = server . config . ContactInfoURL
rootObject [ consoleql . TermsAndConditionsURL ] = server . config . TermsAndConditionsURL
2019-03-02 15:22:20 +00:00
2019-01-24 16:26:36 +00:00
result := graphql . Do ( graphql . Params {
2019-08-08 13:12:39 +01:00
Schema : server . schema ,
2019-01-24 16:26:36 +00:00
Context : ctx ,
RequestString : query . Query ,
VariableValues : query . Variables ,
OperationName : query . OperationName ,
2019-03-02 15:22:20 +00:00
RootObject : rootObject ,
2019-01-24 16:26:36 +00:00
} )
2020-01-20 13:02:44 +00:00
getGqlError := func ( err gqlerrors . FormattedError ) error {
2021-05-14 16:05:42 +01:00
var gerr * gqlerrors . Error
if errors . As ( err . OriginalError ( ) , & gerr ) {
2020-01-20 13:02:44 +00:00
return gerr . OriginalError
}
return nil
}
parseConsoleError := func ( err error ) ( int , error ) {
switch {
case console . ErrUnauthorized . Has ( err ) :
return http . StatusUnauthorized , err
case console . Error . Has ( err ) :
return http . StatusInternalServerError , err
}
return 0 , nil
}
handleErrors := func ( code int , errors gqlerrors . FormattedErrors ) {
w . WriteHeader ( code )
var jsonError struct {
Errors [ ] string ` json:"errors" `
}
for _ , err := range errors {
jsonError . Errors = append ( jsonError . Errors , err . Message )
}
if err := json . NewEncoder ( w ) . Encode ( jsonError ) ; err != nil {
server . log . Error ( "error graphql error" , zap . Error ( err ) )
}
}
handleGraphqlErrors := func ( ) {
for _ , err := range result . Errors {
gqlErr := getGqlError ( err )
if gqlErr == nil {
continue
}
code , err := parseConsoleError ( gqlErr )
if err != nil {
handleError ( code , err )
return
}
}
2020-02-21 11:47:53 +00:00
handleErrors ( http . StatusOK , result . Errors )
2020-01-20 13:02:44 +00:00
}
if result . HasErrors ( ) {
handleGraphqlErrors ( )
return
}
2019-01-24 16:26:36 +00:00
err = json . NewEncoder ( w ) . Encode ( result )
if err != nil {
2020-01-20 13:02:44 +00:00
server . log . Error ( "error encoding grapql result" , zap . Error ( err ) )
2019-01-24 16:26:36 +00:00
return
}
2020-04-13 10:31:17 +01:00
server . log . Debug ( fmt . Sprintf ( "%s" , result ) )
2019-01-24 16:26:36 +00:00
}
2019-12-12 12:58:15 +00:00
// serveError serves error static pages.
func ( server * Server ) serveError ( w http . ResponseWriter , status int ) {
w . WriteHeader ( status )
switch status {
case http . StatusInternalServerError :
2021-11-03 15:36:20 +00:00
templates , err := server . loadTemplates ( )
2019-12-12 12:58:15 +00:00
if err != nil {
2021-11-03 15:36:20 +00:00
server . log . Error ( "unable to load templates" , zap . Error ( err ) )
return
}
err = templates . internalServerError . Execute ( w , nil )
if err != nil {
server . log . Error ( "cannot parse internalServerError template" , zap . Error ( err ) )
2019-12-12 12:58:15 +00:00
}
2020-02-10 12:03:38 +00:00
case http . StatusNotFound :
2021-11-03 15:36:20 +00:00
templates , err := server . loadTemplates ( )
2019-12-12 12:58:15 +00:00
if err != nil {
2021-11-03 15:36:20 +00:00
server . log . Error ( "unable to load templates" , zap . Error ( err ) )
return
}
err = templates . notFound . Execute ( w , nil )
if err != nil {
server . log . Error ( "cannot parse pageNotFound template" , zap . Error ( err ) )
2019-12-12 12:58:15 +00:00
}
}
}
2020-07-16 15:18:02 +01:00
// seoHandler used to communicate with web crawlers and other web robots.
2019-09-09 19:33:05 +01:00
func ( server * Server ) seoHandler ( w http . ResponseWriter , req * http . Request ) {
header := w . Header ( )
header . Set ( contentType , mime . TypeByExtension ( ".txt" ) )
header . Set ( "X-Content-Type-Options" , "nosniff" )
2019-09-27 17:48:53 +01:00
_ , err := w . Write ( [ ] byte ( server . config . SEO ) )
2019-09-09 19:33:05 +01:00
if err != nil {
server . log . Error ( err . Error ( ) )
}
}
2020-12-15 19:06:26 +00:00
// brotliMiddleware is used to compress static content using brotli to minify resources if browser support such decoding.
func ( server * Server ) brotliMiddleware ( fn http . Handler ) http . Handler {
2019-08-08 13:12:39 +01:00
return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
2019-11-12 13:05:35 +00:00
w . Header ( ) . Set ( "Cache-Control" , "public, max-age=31536000" )
w . Header ( ) . Set ( "X-Content-Type-Options" , "nosniff" )
2020-12-15 19:06:26 +00:00
isBrotliSupported := strings . Contains ( r . Header . Get ( "Accept-Encoding" ) , "br" )
if ! isBrotliSupported {
2019-11-12 13:05:35 +00:00
fn . ServeHTTP ( w , r )
return
2019-08-08 13:12:39 +01:00
}
2019-08-13 13:37:01 +01:00
2020-12-15 19:06:26 +00:00
info , err := os . Stat ( server . config . StaticDir + strings . TrimPrefix ( r . URL . Path , "/static" ) + ".br" )
2019-11-12 13:05:35 +00:00
if err != nil {
2019-08-08 13:12:39 +01:00
fn . ServeHTTP ( w , r )
return
}
2019-11-12 13:05:35 +00:00
extension := filepath . Ext ( info . Name ( ) [ : len ( info . Name ( ) ) - 3 ] )
w . Header ( ) . Set ( contentType , mime . TypeByExtension ( extension ) )
2020-12-15 19:06:26 +00:00
w . Header ( ) . Set ( "Content-Encoding" , "br" )
2019-08-08 13:12:39 +01:00
newRequest := new ( http . Request )
* newRequest = * r
newRequest . URL = new ( url . URL )
* newRequest . URL = * r . URL
2020-12-15 19:06:26 +00:00
newRequest . URL . Path += ".br"
2019-08-08 13:12:39 +01:00
fn . ServeHTTP ( w , newRequest )
} )
2019-01-24 16:26:36 +00:00
}
2019-08-13 13:37:01 +01:00
2021-11-03 15:36:20 +00:00
// loadTemplates is used to initialize all templates.
func ( server * Server ) loadTemplates ( ) ( _ * templates , err error ) {
if server . config . Watch {
return server . parseTemplates ( )
}
if server . templatesCache != nil {
return server . templatesCache , nil
}
templates , err := server . parseTemplates ( )
if err != nil {
return nil , Error . Wrap ( err )
}
server . templatesCache = templates
return server . templatesCache , nil
}
func ( server * Server ) parseTemplates ( ) ( _ * templates , err error ) {
var t templates
t . index , err = template . ParseFiles ( filepath . Join ( server . config . StaticDir , "dist" , "index.html" ) )
2019-08-13 13:37:01 +01:00
if err != nil {
server . log . Error ( "dist folder is not generated. use 'npm run build' command" , zap . Error ( err ) )
2021-11-03 15:36:20 +00:00
// Loading index is optional.
2019-08-13 13:37:01 +01:00
}
2021-11-03 15:36:20 +00:00
t . usageReport , err = template . ParseFiles ( filepath . Join ( server . config . StaticDir , "static" , "reports" , "usageReport.html" ) )
2019-08-13 13:37:01 +01:00
if err != nil {
2021-11-03 15:36:20 +00:00
return & t , Error . Wrap ( err )
2019-08-13 13:37:01 +01:00
}
2021-11-03 15:36:20 +00:00
t . notFound , err = template . ParseFiles ( filepath . Join ( server . config . StaticDir , "static" , "errors" , "404.html" ) )
2019-10-31 18:42:28 +00:00
if err != nil {
2021-11-03 15:36:20 +00:00
return & t , Error . Wrap ( err )
2019-10-31 18:42:28 +00:00
}
2021-11-03 15:36:20 +00:00
t . internalServerError , err = template . ParseFiles ( filepath . Join ( server . config . StaticDir , "static" , "errors" , "500.html" ) )
2019-08-13 13:37:01 +01:00
if err != nil {
2021-11-03 15:36:20 +00:00
return & t , Error . Wrap ( err )
2019-08-13 13:37:01 +01:00
}
2021-11-03 15:36:20 +00:00
return & t , nil
2019-08-13 13:37:01 +01:00
}
2021-08-17 20:38:34 +01:00
// NewUserIDRateLimiter constructs a RateLimiter that limits based on user ID.
func NewUserIDRateLimiter ( config web . RateLimiterConfig ) * web . RateLimiter {
return web . NewRateLimiter ( config , func ( r * http . Request ) ( string , error ) {
auth , err := console . GetAuth ( r . Context ( ) )
if err != nil {
return "" , err
}
return auth . User . ID . String ( ) , nil
} )
}