|
| 1 | +package bridge |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "time" |
| 6 | + |
| 7 | + "github.com/basemachina/bridge/bridgehttp" |
| 8 | + "github.com/basemachina/bridge/internal/auth" |
| 9 | + "github.com/basemachina/bridge/internal/ctxtime" |
| 10 | + "github.com/basemachina/bridge/internal/proxy" |
| 11 | + "github.com/go-logr/logr" |
| 12 | +) |
| 13 | + |
| 14 | +const ( |
| 15 | + OKPath = "/ok" |
| 16 | + OKMessage = "bridge is ready" |
| 17 | + ProxyPath = "/htproxy" |
| 18 | +) |
| 19 | + |
| 20 | +// Env stores configuration settings extract from enviromental variables |
| 21 | +// The practice getting from environmental variables comes from https://12factor.net. |
| 22 | +type Env struct { |
| 23 | + // Port is port to listen HTTP server. Default is 8080. |
| 24 | + Port string `envconfig:"PORT" default:"8080" description:"bridge を HTTP としてサーブするために利用します。"` |
| 25 | + |
| 26 | + // LogLevel is INFO or DEBUG. Default is "INFO". |
| 27 | + LogLevel string `envconfig:"LOG_LEVEL" default:"INFO"` |
| 28 | + |
| 29 | + // APIURL is an url of basemachina. |
| 30 | + APIURL string `envconfig:"BASEMACHINA_API_URL" default:"https://api.basemachina.com"` |
| 31 | + |
| 32 | + // FetchInterval is interval to fetch |
| 33 | + FetchInterval time.Duration `envconfig:"FETCH_INTERVAL" default:"1h" description:"認可処理に利用する公開鍵を更新する間隔です。"` |
| 34 | + |
| 35 | + // FetchTimeout is timeout to fetch |
| 36 | + FetchTimeout time.Duration `envconfig:"FETCH_TIMEOUT" default:"10s" description:"認可処理に利用する公開鍵を更新するタイムアウトです。"` |
| 37 | + |
| 38 | + // TenantID is ID of tenant |
| 39 | + TenantID string `envconfig:"TENANT_ID" default:"" description:"認可処理に利用します。設定されると指定されたテナント ID 以外からのリクエストを拒否します。"` |
| 40 | +} |
| 41 | + |
| 42 | +// HTTPHandlerConfig is a config to setup bridge http handler. |
| 43 | +type HTTPHandlerConfig struct { |
| 44 | + Logger logr.Logger |
| 45 | + PublicKeyGetter auth.PublicKeyGetter |
| 46 | + TenantID string |
| 47 | + Middlewares []bridgehttp.Middleware |
| 48 | +} |
| 49 | + |
| 50 | +// NewHTTPHandler is a handler for handling any requests. |
| 51 | +func NewHTTPHandler(c *HTTPHandlerConfig) http.Handler { |
| 52 | + mux := http.NewServeMux() |
| 53 | + mux.HandleFunc(OKPath, func(w http.ResponseWriter, r *http.Request) { |
| 54 | + if r.Method != http.MethodGet { |
| 55 | + w.WriteHeader(http.StatusMethodNotAllowed) |
| 56 | + return |
| 57 | + } |
| 58 | + w.Write([]byte(OKMessage)) |
| 59 | + }) |
| 60 | + middlewares := append(c.Middlewares, |
| 61 | + ctxtime.Middleware(), |
| 62 | + auth.Middleware(&auth.MiddlewareConfig{ |
| 63 | + TenantID: c.TenantID, |
| 64 | + Logger: c.Logger.WithName("auth"), |
| 65 | + PublicKeyGetter: c.PublicKeyGetter, |
| 66 | + }), |
| 67 | + ) |
| 68 | + mux.Handle(ProxyPath, bridgehttp.UseMiddlewares( |
| 69 | + proxy.NewProxy(c.Logger.WithName("proxy")), |
| 70 | + middlewares..., |
| 71 | + )) |
| 72 | + return mux |
| 73 | +} |
0 commit comments