refactor idp

Signed-off-by: Christian Richter <crichter@owncloud.com>
This commit is contained in:
Christian Richter
2022-04-13 17:04:37 +02:00
parent 4404b9741d
commit bfc8db848c
131 changed files with 43 additions and 18176 deletions
+50
View File
@@ -0,0 +1,50 @@
package assets
import (
"net/http"
"github.com/owncloud/ocis/extensions/idp"
"github.com/owncloud/ocis/extensions/idp/pkg/config"
"github.com/owncloud/ocis/ocis-pkg/assetsfs"
"github.com/owncloud/ocis/ocis-pkg/log"
)
// New returns a new http filesystem to serve assets.
func New(opts ...Option) http.FileSystem {
options := newOptions(opts...)
return assetsfs.New(idp.Assets, options.Config.Asset.Path, options.Logger)
}
// Option defines a single option function.
type Option func(o *Options)
// Options defines the available options for this package.
type Options struct {
Logger log.Logger
Config *config.Config
}
// newOptions initializes the available default options.
func newOptions(opts ...Option) Options {
opt := Options{}
for _, o := range opts {
o(&opt)
}
return opt
}
// Logger provides a function to set the logger option.
func Logger(val log.Logger) Option {
return func(o *Options) {
o.Logger = val
}
}
// Config provides a function to set the config option.
func Config(val *config.Config) Option {
return func(o *Options) {
o.Config = val
}
}
+53
View File
@@ -0,0 +1,53 @@
package command
import (
"fmt"
"net/http"
"github.com/owncloud/ocis/extensions/idp/pkg/config"
"github.com/owncloud/ocis/extensions/idp/pkg/config/parser"
"github.com/owncloud/ocis/extensions/idp/pkg/logging"
"github.com/urfave/cli/v2"
)
// Health is the entrypoint for the health command.
func Health(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "health",
Usage: "check health status",
Category: "info",
Before: func(c *cli.Context) error {
return parser.ParseConfig(cfg)
},
Action: func(c *cli.Context) error {
logger := logging.Configure(cfg.Service.Name, cfg.Log)
resp, err := http.Get(
fmt.Sprintf(
"http://%s/healthz",
cfg.Debug.Addr,
),
)
if err != nil {
logger.Fatal().
Err(err).
Msg("Failed to request health check")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
logger.Fatal().
Int("code", resp.StatusCode).
Msg("Health seems to be in bad state")
}
logger.Debug().
Int("code", resp.StatusCode).
Msg("Health got a good state")
return nil
},
}
}
+64
View File
@@ -0,0 +1,64 @@
package command
import (
"context"
"os"
"github.com/owncloud/ocis/extensions/idp/pkg/config"
"github.com/owncloud/ocis/ocis-pkg/clihelper"
ociscfg "github.com/owncloud/ocis/ocis-pkg/config"
"github.com/thejerf/suture/v4"
"github.com/urfave/cli/v2"
)
// GetCommands provides all commands for this service
func GetCommands(cfg *config.Config) cli.Commands {
return []*cli.Command{
// start this service
Server(cfg),
// interaction with this service
// infos about this service
Health(cfg),
Version(cfg),
}
}
// Execute is the entry point for the ocis-idp command.
func Execute(cfg *config.Config) error {
app := clihelper.DefaultApp(&cli.App{
Name: "ocis-idp",
Usage: "Serve IDP API for oCIS",
Commands: GetCommands(cfg),
})
cli.HelpFlag = &cli.BoolFlag{
Name: "help,h",
Usage: "Show the help",
}
return app.Run(os.Args)
}
// SutureService allows for the idp command to be embedded and supervised by a suture supervisor tree.
type SutureService struct {
cfg *config.Config
}
// NewSutureService creates a new idp.SutureService
func NewSutureService(cfg *ociscfg.Config) suture.Service {
cfg.IDP.Commons = cfg.Commons
return SutureService{
cfg: cfg.IDP,
}
}
func (s SutureService) Serve(ctx context.Context) error {
s.cfg.Context = ctx
if err := Execute(s.cfg); err != nil {
return err
}
return nil
}
+98
View File
@@ -0,0 +1,98 @@
package command
import (
"context"
"fmt"
"github.com/oklog/run"
"github.com/owncloud/ocis/extensions/idp/pkg/config"
"github.com/owncloud/ocis/extensions/idp/pkg/config/parser"
"github.com/owncloud/ocis/extensions/idp/pkg/logging"
"github.com/owncloud/ocis/extensions/idp/pkg/metrics"
"github.com/owncloud/ocis/extensions/idp/pkg/server/debug"
"github.com/owncloud/ocis/extensions/idp/pkg/server/http"
"github.com/owncloud/ocis/extensions/idp/pkg/tracing"
"github.com/owncloud/ocis/ocis-pkg/version"
"github.com/urfave/cli/v2"
)
// Server is the entrypoint for the server command.
func Server(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "server",
Usage: fmt.Sprintf("start %s extension without runtime (unsupervised mode)", cfg.Service.Name),
Category: "server",
Before: func(c *cli.Context) error {
return parser.ParseConfig(cfg)
},
Action: func(c *cli.Context) error {
logger := logging.Configure(cfg.Service.Name, cfg.Log)
err := tracing.Configure(cfg)
if err != nil {
return err
}
var (
gr = run.Group{}
ctx, cancel = func() (context.Context, context.CancelFunc) {
if cfg.Context == nil {
return context.WithCancel(context.Background())
}
return context.WithCancel(cfg.Context)
}()
metrics = metrics.New()
)
defer cancel()
metrics.BuildInfo.WithLabelValues(version.String).Set(1)
{
server, err := http.Server(
http.Logger(logger),
http.Context(ctx),
http.Config(cfg),
http.Metrics(metrics),
)
if err != nil {
logger.Info().
Err(err).
Str("transport", "http").
Msg("Failed to initialize server")
return err
}
gr.Add(func() error {
return server.Run()
}, func(_ error) {
logger.Info().
Str("transport", "http").
Msg("Shutting down server")
cancel()
})
}
{
server, err := debug.Server(
debug.Logger(logger),
debug.Context(ctx),
debug.Config(cfg),
)
if err != nil {
logger.Info().Err(err).Str("transport", "debug").Msg("Failed to initialize server")
return err
}
gr.Add(server.ListenAndServe, func(_ error) {
_ = server.Shutdown(ctx)
cancel()
})
}
return gr.Run()
},
}
}
+50
View File
@@ -0,0 +1,50 @@
package command
import (
"fmt"
"os"
"github.com/owncloud/ocis/ocis-pkg/registry"
"github.com/owncloud/ocis/ocis-pkg/version"
tw "github.com/olekukonko/tablewriter"
"github.com/owncloud/ocis/extensions/idp/pkg/config"
"github.com/urfave/cli/v2"
)
// Version prints the service versions of all running instances.
func Version(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "version",
Usage: "print the version of this binary and the running extension instances",
Category: "info",
Action: func(c *cli.Context) error {
fmt.Println("Version: " + version.String)
fmt.Printf("Compiled: %s\n", version.Compiled())
fmt.Println("")
reg := registry.GetRegistry()
services, err := reg.GetService(cfg.HTTP.Namespace + "." + cfg.Service.Name)
if err != nil {
fmt.Println(fmt.Errorf("could not get %s services from the registry: %v", cfg.Service.Name, err))
return err
}
if len(services) == 0 {
fmt.Println("No running " + cfg.Service.Name + " service found.")
return nil
}
table := tw.NewWriter(os.Stdout)
table.SetHeader([]string{"Version", "Address", "Id"})
table.SetAutoFormatHeaders(false)
for _, s := range services {
for _, n := range s.Nodes {
table.Append([]string{s.Version, n.Address, n.Id})
}
}
table.Render()
return nil
},
}
}
+102
View File
@@ -0,0 +1,102 @@
package config
import (
"context"
"github.com/owncloud/ocis/ocis-pkg/shared"
)
// Config combines all available configuration parts.
type Config struct {
*shared.Commons `yaml:"-"`
Service Service `yaml:"-"`
Tracing *Tracing `yaml:"tracing"`
Log *Log `yaml:"log"`
Debug Debug `yaml:"debug"`
HTTP HTTP `yaml:"http"`
Asset Asset `yaml:"asset"`
IDP Settings `yaml:"idp"`
Ldap Ldap `yaml:"ldap"`
Context context.Context `yaml:"-"`
}
// Ldap defines the available LDAP configuration.
type Ldap struct {
URI string `yaml:"uri" env:"LDAP_URI;IDP_LDAP_URI"`
BindDN string `yaml:"bind_dn" env:"LDAP_BIND_DN;IDP_LDAP_BIND_DN"`
BindPassword string `yaml:"bind_password" env:"LDAP_BIND_PASSWORD;IDP_LDAP_BIND_PASSWORD"`
BaseDN string `yaml:"base_dn" env:"LDAP_USER_BASE_DN,IDP_LDAP_BASE_DN"`
Scope string `yaml:"scope" env:"LDAP_USER_SCOPE;IDP_LDAP_SCOPE"`
LoginAttribute string `yaml:"login_attribute" env:"IDP_LDAP_LOGIN_ATTRIBUTE"`
EmailAttribute string `yaml:"email_attribute" env:"LDAP_USER_SCHEMA_MAIL;IDP_LDAP_EMAIL_ATTRIBUTE"`
NameAttribute string `yaml:"name_attribute" env:"LDAP_USER_SCHEMA_USERNAME;IDP_LDAP_NAME_ATTRIBUTE"`
UUIDAttribute string `yaml:"uuid_attribute" env:"LDAP_USER_SCHEMA_ID;IDP_LDAP_UUID_ATTRIBUTE"`
UUIDAttributeType string `yaml:"uuid_attribute_type" env:"IDP_LDAP_UUID_ATTRIBUTE_TYPE"`
Filter string `yaml:"filter" env:"LDAP_USER_FILTER;IDP_LDAP_FILTER"`
ObjectClass string `yaml:"objectclass" env:"LDAP_USER_OBJECTCLASS;IDP_LDAP_OBJECTCLASS"`
}
// Asset defines the available asset configuration.
type Asset struct {
Path string `yaml:"asset" env:"IDP_ASSET_PATH"`
}
type Settings struct {
// don't change the order of elements in this struct
// it needs to match github.com/libregraph/lico/bootstrap.Settings
Iss string `yaml:"iss" env:"OCIS_URL;IDP_ISS"`
IdentityManager string `yaml:"identity_manager" env:"IDP_IDENTITY_MANAGER"`
URIBasePath string `yaml:"uri_base_path" env:"IDP_URI_BASE_PATH"`
SignInURI string `yaml:"sign_in_uri" env:"IDP_SIGN_IN_URI"`
SignedOutURI string `yaml:"signed_out_uri" env:"IDP_SIGN_OUT_URI"`
AuthorizationEndpointURI string `yaml:"authorization_endpoint_uri" env:"IDP_ENDPOINT_URI"`
EndsessionEndpointURI string `yaml:"end_session_endpoint_uri" env:"IDP_ENDSESSION_ENDPOINT_URI"`
Insecure bool `yaml:"insecure" env:"IDP_INSECURE"`
TrustedProxy []string `yaml:"trusted_proxy"` //TODO: how to configure this via env?
AllowScope []string `yaml:"allow_scope"` // TODO: is this even needed?
AllowClientGuests bool `yaml:"allow_client_guests" env:"IDP_ALLOW_CLIENT_GUESTS"`
AllowDynamicClientRegistration bool `yaml:"allow_dynamic_client_registration" env:"IDP_ALLOW_DYNAMIC_CLIENT_REGISTRATION"`
EncryptionSecretFile string `yaml:"encrypt_secret_file" env:"IDP_ENCRYPTION_SECRET"`
Listen string
IdentifierClientDisabled bool `yaml:"identifier_client_disabled" env:"IDP_DISABLE_IDENTIFIER_WEBAPP"`
IdentifierClientPath string `yaml:"identifier_client_path" env:"IDP_IDENTIFIER_CLIENT_PATH"`
IdentifierRegistrationConf string `yaml:"identifier_registration_conf" env:"IDP_IDENTIFIER_REGISTRATION_CONF"`
IdentifierScopesConf string `yaml:"identifier_scopes_conf" env:"IDP_IDENTIFIER_SCOPES_CONF"`
IdentifierDefaultBannerLogo string
IdentifierDefaultSignInPageText string
IdentifierDefaultUsernameHintText string
IdentifierUILocales []string
SigningKid string `yaml:"signing_kid" env:"IDP_SIGNING_KID"`
SigningMethod string `yaml:"signing_method" env:"IDP_SIGNING_METHOD"`
SigningPrivateKeyFiles []string `yaml:"signing_private_key_files"` // TODO: is this even needed?
ValidationKeysPath string `yaml:"validation_keys_path" env:"IDP_VALIDATION_KEYS_PATH"`
CookieBackendURI string
CookieNames []string
AccessTokenDurationSeconds uint64 `yaml:"access_token_duration_seconds" env:"IDP_ACCESS_TOKEN_EXPIRATION"`
IDTokenDurationSeconds uint64 `yaml:"id_token_duration_seconds" env:"IDP_ID_TOKEN_EXPIRATION"`
RefreshTokenDurationSeconds uint64 `yaml:"refresh_token_duration_seconds" env:"IDP_REFRESH_TOKEN_EXPIRATION"`
DyamicClientSecretDurationSeconds uint64 `yaml:"dynamic_client_secret_duration_seconds" env:""`
}
+9
View File
@@ -0,0 +1,9 @@
package config
// Debug defines the available debug configuration.
type Debug struct {
Addr string `yaml:"addr" env:"IDP_DEBUG_ADDR"`
Token string `yaml:"token" env:"IDP_DEBUG_TOKEN"`
Pprof bool `yaml:"pprof" env:"IDP_DEBUG_PPROF"`
Zpages bool `yaml:"zpages" env:"IDP_DEBUG_ZPAGES"`
}
@@ -0,0 +1,117 @@
package defaults
import (
"path"
"strings"
"github.com/owncloud/ocis/extensions/idp/pkg/config"
"github.com/owncloud/ocis/ocis-pkg/config/defaults"
)
func FullDefaultConfig() *config.Config {
cfg := DefaultConfig()
EnsureDefaults(cfg)
Sanitize(cfg)
return cfg
}
func DefaultConfig() *config.Config {
return &config.Config{
Debug: config.Debug{
Addr: "127.0.0.1:9134",
},
HTTP: config.HTTP{
Addr: "127.0.0.1:9130",
Root: "/",
Namespace: "com.owncloud.web",
TLSCert: path.Join(defaults.BaseDataPath(), "idp", "server.crt"),
TLSKey: path.Join(defaults.BaseDataPath(), "idp", "server.key"),
TLS: false,
},
Service: config.Service{
Name: "idp",
},
Asset: config.Asset{},
IDP: config.Settings{
Iss: "https://localhost:9200",
IdentityManager: "ldap",
URIBasePath: "",
SignInURI: "",
SignedOutURI: "",
AuthorizationEndpointURI: "",
EndsessionEndpointURI: "",
Insecure: false,
TrustedProxy: nil,
AllowScope: nil,
AllowClientGuests: false,
AllowDynamicClientRegistration: false,
EncryptionSecretFile: "",
Listen: "",
IdentifierClientDisabled: true,
IdentifierClientPath: path.Join(defaults.BaseDataPath(), "idp"),
IdentifierRegistrationConf: path.Join(defaults.BaseDataPath(), "idp", "identifier-registration.yaml"),
IdentifierScopesConf: "",
IdentifierDefaultBannerLogo: "",
IdentifierDefaultSignInPageText: "",
IdentifierDefaultUsernameHintText: "",
SigningKid: "",
SigningMethod: "PS256",
SigningPrivateKeyFiles: nil,
ValidationKeysPath: "",
CookieBackendURI: "",
CookieNames: nil,
AccessTokenDurationSeconds: 60 * 10, // 10 minutes
IDTokenDurationSeconds: 60 * 60, // 1 hour
RefreshTokenDurationSeconds: 60 * 60 * 24 * 365 * 3, // 1 year
DyamicClientSecretDurationSeconds: 0,
},
Ldap: config.Ldap{
URI: "ldap://localhost:9125",
BindDN: "cn=idp,ou=sysusers,dc=ocis,dc=test",
BindPassword: "idp",
BaseDN: "ou=users,dc=ocis,dc=test",
Scope: "sub",
LoginAttribute: "cn",
EmailAttribute: "mail",
NameAttribute: "displayName",
UUIDAttribute: "uid",
UUIDAttributeType: "text",
Filter: "",
ObjectClass: "posixAccount",
},
}
}
func EnsureDefaults(cfg *config.Config) {
// provide with defaults for shared logging, since we need a valid destination address for BindEnv.
if cfg.Log == nil && cfg.Commons != nil && cfg.Commons.Log != nil {
cfg.Log = &config.Log{
Level: cfg.Commons.Log.Level,
Pretty: cfg.Commons.Log.Pretty,
Color: cfg.Commons.Log.Color,
File: cfg.Commons.Log.File,
}
} else if cfg.Log == nil {
cfg.Log = &config.Log{}
}
// provide with defaults for shared tracing, since we need a valid destination address for BindEnv.
if cfg.Tracing == nil && cfg.Commons != nil && cfg.Commons.Tracing != nil {
cfg.Tracing = &config.Tracing{
Enabled: cfg.Commons.Tracing.Enabled,
Type: cfg.Commons.Tracing.Type,
Endpoint: cfg.Commons.Tracing.Endpoint,
Collector: cfg.Commons.Tracing.Collector,
}
} else if cfg.Tracing == nil {
cfg.Tracing = &config.Tracing{}
}
}
func Sanitize(cfg *config.Config) {
// sanitize config
if cfg.HTTP.Root != "/" {
cfg.HTTP.Root = strings.TrimSuffix(cfg.HTTP.Root, "/")
}
}
+11
View File
@@ -0,0 +1,11 @@
package config
// HTTP defines the available http configuration.
type HTTP struct {
Addr string `yaml:"addr" env:"IDP_HTTP_ADDR"`
Root string `yaml:"root" env:"IDP_HTTP_ROOT"`
Namespace string `yaml:"-"`
TLSCert string `yaml:"tls_cert" env:"IDP_TRANSPORT_TLS_CERT"`
TLSKey string `yaml:"tls_key" env:"IDP_TRANSPORT_TLS_KEY"`
TLS bool `yaml:"tls" env:"IDP_TLS"`
}
+9
View File
@@ -0,0 +1,9 @@
package config
// Log defines the available log configuration.
type Log struct {
Level string `yaml:"level" env:"OCIS_LOG_LEVEL;IDP_LOG_LEVEL"`
Pretty bool `yaml:"pretty" env:"OCIS_LOG_PRETTY;IDP_LOG_PRETTY"`
Color bool `yaml:"color" env:"OCIS_LOG_COLOR;IDP_LOG_COLOR"`
File string `yaml:"file" env:"OCIS_LOG_FILE;IDP_LOG_FILE"`
}
+33
View File
@@ -0,0 +1,33 @@
package parser
import (
"errors"
"github.com/owncloud/ocis/extensions/idp/pkg/config"
"github.com/owncloud/ocis/extensions/idp/pkg/config/defaults"
ociscfg "github.com/owncloud/ocis/ocis-pkg/config"
"github.com/owncloud/ocis/ocis-pkg/config/envdecode"
)
// ParseConfig loads accounts configuration from known paths.
func ParseConfig(cfg *config.Config) error {
_, err := ociscfg.BindSourcesToStructs(cfg.Service.Name, cfg)
if err != nil {
return err
}
defaults.EnsureDefaults(cfg)
// load all env variables relevant to the config in the current context.
if err := envdecode.Decode(cfg); err != nil {
// no environment variable set for this config is an expected "error"
if !errors.Is(err, envdecode.ErrNoTargetFieldsAreSet) {
return err
}
}
defaults.Sanitize(cfg)
return nil
}
+7
View File
@@ -0,0 +1,7 @@
package config
// Service defines the available service configuration.
type Service struct {
Name string `yaml:"-"`
PasswordResetURI string `yaml:"password_reset_uri" env:"IDP_PASSWORD_RESET_URI" desc:"The URI where a user can reset their password."`
}
+9
View File
@@ -0,0 +1,9 @@
package config
// Tracing defines the available tracing configuration.
type Tracing struct {
Enabled bool `yaml:"enabled" env:"OCIS_TRACING_ENABLED;IDP_TRACING_ENABLED"`
Type string `yaml:"type" env:"OCIS_TRACING_TYPE;IDP_TRACING_TYPE"`
Endpoint string `yaml:"endpoint" env:"OCIS_TRACING_ENDPOINT;IDP_TRACING_ENDPOINT"`
Collector string `yaml:"collector" env:"OCIS_TRACING_COLLECTOR;IDP_TRACING_COLLECTOR"`
}
+17
View File
@@ -0,0 +1,17 @@
package logging
import (
"github.com/owncloud/ocis/extensions/idp/pkg/config"
"github.com/owncloud/ocis/ocis-pkg/log"
)
// LoggerFromConfig initializes a service-specific logger instance.
func Configure(name string, cfg *config.Log) log.Logger {
return log.NewLogger(
log.Name(name),
log.Level(cfg.Level),
log.Pretty(cfg.Pretty),
log.Color(cfg.Color),
log.File(cfg.File),
)
}
+45
View File
@@ -0,0 +1,45 @@
package metrics
import "github.com/prometheus/client_golang/prometheus"
var (
// Namespace defines the namespace for the defines metrics.
Namespace = "ocis"
// Subsystem defines the subsystem for the defines metrics.
Subsystem = "idp"
)
// Metrics defines the available metrics of this service.
type Metrics struct {
// Counter *prometheus.CounterVec
BuildInfo *prometheus.GaugeVec
}
// New initializes the available metrics.
func New() *Metrics {
m := &Metrics{
// Counter: prometheus.NewCounterVec(prometheus.CounterOpts{
// Namespace: Namespace,
// Subsystem: Subsystem,
// Name: "greet_total",
// Help: "How many greeting requests processed",
// }, []string{}),
BuildInfo: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: Namespace,
Subsystem: Subsystem,
Name: "build_info",
Help: "Build Information",
}, []string{"version"}),
}
// prometheus.Register(
// m.Counter,
// )
_ = prometheus.Register(
m.BuildInfo,
)
return m
}
+51
View File
@@ -0,0 +1,51 @@
package middleware
import (
"net/http"
"strings"
idpTracing "github.com/owncloud/ocis/extensions/idp/pkg/tracing"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
)
// Static is a middleware that serves static assets.
func Static(root string, fs http.FileSystem) func(http.Handler) http.Handler {
if !strings.HasSuffix(root, "/") {
root = root + "/"
}
static := http.StripPrefix(
root,
http.FileServer(
fs,
),
)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, span := idpTracing.TraceProvider.Tracer("idp").Start(r.Context(), "serve static asset")
defer span.End()
r = r.WithContext(ctx)
// serve the static assets for the identifier web app
if strings.HasPrefix(r.URL.Path, "/signin/v1/static/") {
if strings.HasSuffix(r.URL.Path, "/") {
// but no listing of folders
span.SetAttributes(attribute.KeyValue{Key: "path", Value: attribute.StringValue(r.URL.Path)})
span.SetStatus(codes.Error, "asset not found")
http.NotFound(w, r)
} else {
r.URL.Path = strings.Replace(r.URL.Path, "/signin/v1/static/", "/signin/v1/identifier/static/", 1)
span.SetAttributes(attribute.KeyValue{Key: "server", Value: attribute.StringValue(r.URL.Path)})
static.ServeHTTP(w, r)
}
return
}
span.SetAttributes(attribute.KeyValue{Key: "path", Value: attribute.StringValue(r.URL.Path)})
span.SetStatus(codes.Ok, "ok")
next.ServeHTTP(w, r)
})
}
}
+50
View File
@@ -0,0 +1,50 @@
package debug
import (
"context"
"github.com/owncloud/ocis/extensions/idp/pkg/config"
"github.com/owncloud/ocis/ocis-pkg/log"
)
// Option defines a single option function.
type Option func(o *Options)
// Options defines the available options for this package.
type Options struct {
Logger log.Logger
Context context.Context
Config *config.Config
}
// newOptions initializes the available default options.
func newOptions(opts ...Option) Options {
opt := Options{}
for _, o := range opts {
o(&opt)
}
return opt
}
// Logger provides a function to set the logger option.
func Logger(val log.Logger) Option {
return func(o *Options) {
o.Logger = val
}
}
// Context provides a function to set the context option.
func Context(val context.Context) Option {
return func(o *Options) {
o.Context = val
}
}
// Config provides a function to set the config option.
func Config(val *config.Config) Option {
return func(o *Options) {
o.Config = val
}
}
+70
View File
@@ -0,0 +1,70 @@
package debug
import (
"io"
"net/http"
"net/url"
"github.com/owncloud/ocis/extensions/idp/pkg/config"
"github.com/owncloud/ocis/ocis-pkg/log"
"github.com/owncloud/ocis/ocis-pkg/service/debug"
"github.com/owncloud/ocis/ocis-pkg/shared"
"github.com/owncloud/ocis/ocis-pkg/version"
)
// Server initializes the debug service and server.
func Server(opts ...Option) (*http.Server, error) {
options := newOptions(opts...)
return debug.NewService(
debug.Logger(options.Logger),
debug.Name(options.Config.Service.Name),
debug.Version(version.String),
debug.Address(options.Config.Debug.Addr),
debug.Token(options.Config.Debug.Token),
debug.Pprof(options.Config.Debug.Pprof),
debug.Zpages(options.Config.Debug.Zpages),
debug.Health(health(options.Config, options.Logger)),
debug.Ready(ready(options.Config)),
), nil
}
// health implements the health check.
func health(cfg *config.Config, l log.Logger) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
targetHost, err := url.Parse(cfg.Ldap.URI)
if err != nil {
l.Fatal().Err(err).Str("uri", cfg.Ldap.URI).Msg("invalid LDAP URI")
}
err = shared.RunChecklist(shared.TCPConnect(targetHost.Host))
retVal := http.StatusOK
if err != nil {
l.Error().Err(err).Msg("Healtcheck failed")
retVal = http.StatusInternalServerError
}
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(retVal)
_, err = io.WriteString(w, http.StatusText(retVal))
if err != nil {
l.Fatal().Err(err).Msg("Could not write health check body")
}
}
}
// ready implements the ready check.
func ready(cfg *config.Config) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
// if we can call this function, a http(200) is a valid response as
// there is nothing we can check at this point for IDP
// if there is a mishap when initializing, there is a minimal (talking ms or ns window)
// timeframe where this code is callable
_, err := io.WriteString(w, http.StatusText(http.StatusOK))
// io.WriteString should not fail but if it does we want to know.
if err != nil {
panic(err)
}
}
}
+76
View File
@@ -0,0 +1,76 @@
package http
import (
"context"
"github.com/owncloud/ocis/extensions/idp/pkg/config"
"github.com/owncloud/ocis/extensions/idp/pkg/metrics"
"github.com/owncloud/ocis/ocis-pkg/log"
"github.com/urfave/cli/v2"
)
// Option defines a single option function.
type Option func(o *Options)
// Options defines the available options for this package.
type Options struct {
Namespace string
Logger log.Logger
Context context.Context
Config *config.Config
Metrics *metrics.Metrics
Flags []cli.Flag
}
// newOptions initializes the available default options.
func newOptions(opts ...Option) Options {
opt := Options{}
for _, o := range opts {
o(&opt)
}
return opt
}
// Logger provides a function to set the logger option.
func Logger(val log.Logger) Option {
return func(o *Options) {
o.Logger = val
}
}
// Context provides a function to set the context option.
func Context(val context.Context) Option {
return func(o *Options) {
o.Context = val
}
}
// Config provides a function to set the config option.
func Config(val *config.Config) Option {
return func(o *Options) {
o.Config = val
}
}
// Metrics provides a function to set the metrics option.
func Metrics(val *metrics.Metrics) Option {
return func(o *Options) {
o.Metrics = val
}
}
// Flags provides a function to set the flags option.
func Flags(val []cli.Flag) Option {
return func(o *Options) {
o.Flags = append(o.Flags, val...)
}
}
// Namespace provides a function to set the namespace option.
func Namespace(val string) Option {
return func(o *Options) {
o.Namespace = val
}
}
+82
View File
@@ -0,0 +1,82 @@
package http
import (
"crypto/tls"
"os"
chimiddleware "github.com/go-chi/chi/v5/middleware"
svc "github.com/owncloud/ocis/extensions/idp/pkg/service/v0"
pkgcrypto "github.com/owncloud/ocis/ocis-pkg/crypto"
"github.com/owncloud/ocis/ocis-pkg/middleware"
"github.com/owncloud/ocis/ocis-pkg/service/http"
"github.com/owncloud/ocis/ocis-pkg/version"
"go-micro.dev/v4"
)
// Server initializes the http service and server.
func Server(opts ...Option) (http.Service, error) {
options := newOptions(opts...)
var tlsConfig *tls.Config
if options.Config.HTTP.TLS {
_, certErr := os.Stat(options.Config.HTTP.TLSCert)
_, keyErr := os.Stat(options.Config.HTTP.TLSKey)
if os.IsNotExist(certErr) || os.IsNotExist(keyErr) {
options.Logger.Info().Msgf("Generating certs")
if err := pkgcrypto.GenCert(options.Config.HTTP.TLSCert, options.Config.HTTP.TLSKey, options.Logger); err != nil {
options.Logger.Fatal().Err(err).Msg("Could not setup TLS")
os.Exit(1)
}
}
cer, err := tls.LoadX509KeyPair(options.Config.HTTP.TLSCert, options.Config.HTTP.TLSKey)
if err != nil {
options.Logger.Fatal().Err(err).Msg("Could not setup TLS")
os.Exit(1)
}
tlsConfig = &tls.Config{MinVersion: tls.VersionTLS12, Certificates: []tls.Certificate{cer}}
}
service := http.NewService(
http.Logger(options.Logger),
http.Namespace(options.Config.HTTP.Namespace),
http.Name(options.Config.Service.Name),
http.Version(version.String),
http.Address(options.Config.HTTP.Addr),
http.Context(options.Context),
http.Flags(options.Flags...),
http.TLSConfig(tlsConfig),
)
handle := svc.NewService(
svc.Logger(options.Logger),
svc.Config(options.Config),
svc.Middleware(
chimiddleware.RealIP,
chimiddleware.RequestID,
middleware.TraceContext,
middleware.NoCache,
middleware.Secure,
middleware.Version(
options.Config.Service.Name,
version.String,
),
middleware.Logger(
options.Logger,
),
),
)
{
handle = svc.NewInstrument(handle, options.Metrics)
handle = svc.NewLoggingHandler(handle, options.Logger)
}
if err := micro.RegisterHandler(service.Server(), handle); err != nil {
return http.Service{}, err
}
return service, nil
}
@@ -0,0 +1,25 @@
package svc
import (
"net/http"
"github.com/owncloud/ocis/extensions/idp/pkg/metrics"
)
// NewInstrument returns a service that instruments metrics.
func NewInstrument(next Service, metrics *metrics.Metrics) Service {
return instrument{
next: next,
metrics: metrics,
}
}
type instrument struct {
next Service
metrics *metrics.Metrics
}
// ServeHTTP implements the Service interface.
func (i instrument) ServeHTTP(w http.ResponseWriter, r *http.Request) {
i.next.ServeHTTP(w, r)
}
+25
View File
@@ -0,0 +1,25 @@
package svc
import (
"net/http"
"github.com/owncloud/ocis/ocis-pkg/log"
)
// NewLogging returns a service that logs messages.
func NewLoggingHandler(next Service, logger log.Logger) Service {
return loggingHandler{
next: next,
logger: logger,
}
}
type loggingHandler struct {
next Service
logger log.Logger
}
// ServeHTTP implements the Service interface.
func (l loggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
l.next.ServeHTTP(w, r)
}
+50
View File
@@ -0,0 +1,50 @@
package svc
import (
"net/http"
"github.com/owncloud/ocis/extensions/idp/pkg/config"
"github.com/owncloud/ocis/ocis-pkg/log"
)
// Option defines a single option function.
type Option func(o *Options)
// Options defines the available options for this package.
type Options struct {
Logger log.Logger
Config *config.Config
Middleware []func(http.Handler) http.Handler
}
// newOptions initializes the available default options.
func newOptions(opts ...Option) Options {
opt := Options{}
for _, o := range opts {
o(&opt)
}
return opt
}
// Logger provides a function to set the logger option.
func Logger(val log.Logger) Option {
return func(o *Options) {
o.Logger = val
}
}
// Config provides a function to set the config option.
func Config(val *config.Config) Option {
return func(o *Options) {
o.Config = val
}
}
// Middleware provides a function to set the middleware option.
func Middleware(val ...func(http.Handler) http.Handler) Option {
return func(o *Options) {
o.Middleware = val
}
}
+229
View File
@@ -0,0 +1,229 @@
package svc
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"strings"
"github.com/go-chi/chi/v5"
"github.com/gorilla/mux"
"github.com/libregraph/lico/bootstrap"
dummyBackendSupport "github.com/libregraph/lico/bootstrap/backends/dummy"
guestBackendSupport "github.com/libregraph/lico/bootstrap/backends/guest"
kcBackendSupport "github.com/libregraph/lico/bootstrap/backends/kc"
ldapBackendSupport "github.com/libregraph/lico/bootstrap/backends/ldap"
licoconfig "github.com/libregraph/lico/config"
"github.com/libregraph/lico/server"
"github.com/owncloud/ocis/extensions/idp/pkg/assets"
"github.com/owncloud/ocis/extensions/idp/pkg/config"
"github.com/owncloud/ocis/extensions/idp/pkg/middleware"
"github.com/owncloud/ocis/ocis-pkg/log"
"stash.kopano.io/kgol/rndm"
)
// Service defines the extension handlers.
type Service interface {
ServeHTTP(http.ResponseWriter, *http.Request)
}
// NewService returns a service implementation for Service.
func NewService(opts ...Option) Service {
ctx := context.Background()
options := newOptions(opts...)
logger := options.Logger.Logger
assetVFS := assets.New(
assets.Logger(options.Logger),
assets.Config(options.Config),
)
if err := initLicoInternalEnvVars(&options.Config.Ldap); err != nil {
logger.Fatal().Err(err).Msg("could not initialize env vars")
}
if err := createConfigsIfNotExist(assetVFS, options.Config.IDP.IdentifierRegistrationConf, options.Config.IDP.Iss); err != nil {
logger.Fatal().Err(err).Msg("could not create default config")
}
guestBackendSupport.MustRegister()
ldapBackendSupport.MustRegister()
dummyBackendSupport.MustRegister()
kcBackendSupport.MustRegister()
// https://play.golang.org/p/Mh8AVJCd593
idpSettings := bootstrap.Settings(options.Config.IDP)
bs, err := bootstrap.Boot(ctx, &idpSettings, &licoconfig.Config{
Logger: log.LogrusWrap(logger),
})
if err != nil {
logger.Fatal().Err(err).Msg("could not bootstrap idp")
}
managers := bs.Managers()
routes := []server.WithRoutes{managers.Must("identity").(server.WithRoutes)}
handlers := managers.Must("handler").(http.Handler)
svc := IDP{
logger: options.Logger,
config: options.Config,
assets: assetVFS,
}
svc.initMux(ctx, routes, handlers, options)
return svc
}
func createConfigsIfNotExist(assets http.FileSystem, filePath, ocisURL string) error {
folder := path.Dir(filePath)
if _, err := os.Stat(folder); os.IsNotExist(err) {
if err := os.MkdirAll(folder, 0700); err != nil {
return err
}
}
if _, err := os.Stat(filePath); os.IsNotExist(err) {
defaultConf, err := assets.Open("/identifier-registration.yaml")
if err != nil {
return err
}
defer defaultConf.Close()
confOnDisk, err := os.Create(filePath)
if err != nil {
return err
}
defer confOnDisk.Close()
conf, err := ioutil.ReadAll(defaultConf)
if err != nil {
return err
}
// replace placeholder {{OCIS_URL}} with https://localhost:9200 / correct host
conf = []byte(strings.ReplaceAll(string(conf), "{{OCIS_URL}}", strings.TrimRight(ocisURL, "/")))
err = ioutil.WriteFile(filePath, conf, 0600)
if err != nil {
return err
}
}
return nil
}
// Init vars which are currently not accessible via idp api
func initLicoInternalEnvVars(ldap *config.Ldap) error {
filter := fmt.Sprintf("(objectclass=%s)", ldap.ObjectClass)
if ldap.Filter != "" {
filter = fmt.Sprintf("(&%s%s)", ldap.Filter, filter)
}
var defaults = map[string]string{
"LDAP_URI": ldap.URI,
"LDAP_BINDDN": ldap.BindDN,
"LDAP_BINDPW": ldap.BindPassword,
"LDAP_BASEDN": ldap.BaseDN,
"LDAP_SCOPE": ldap.Scope,
"LDAP_LOGIN_ATTRIBUTE": ldap.LoginAttribute,
"LDAP_EMAIL_ATTRIBUTE": ldap.EmailAttribute,
"LDAP_NAME_ATTRIBUTE": ldap.NameAttribute,
"LDAP_UUID_ATTRIBUTE": ldap.UUIDAttribute,
"LDAP_UUID_ATTRIBUTE_TYPE": ldap.UUIDAttributeType,
"LDAP_FILTER": filter,
}
for k, v := range defaults {
if err := os.Setenv(k, v); err != nil {
return fmt.Errorf("could not set env var %s=%s", k, v)
}
}
return nil
}
// IDP defines implements the business logic for Service.
type IDP struct {
logger log.Logger
config *config.Config
mux *chi.Mux
assets http.FileSystem
}
// initMux initializes the internal idp gorilla mux and mounts it in to a ocis chi-router
func (idp *IDP) initMux(ctx context.Context, r []server.WithRoutes, h http.Handler, options Options) {
gm := mux.NewRouter()
for _, route := range r {
route.AddRoutes(ctx, gm)
}
// Delegate rest to provider which is also a handler.
if h != nil {
gm.NotFoundHandler = h
}
idp.mux = chi.NewMux()
idp.mux.Use(options.Middleware...)
idp.mux.Use(middleware.Static(
"/signin/v1/",
assets.New(
assets.Logger(options.Logger),
assets.Config(options.Config),
),
))
// handle / | index.html with a template that needs to have the BASE_PREFIX replaced
idp.mux.Get("/signin/v1/identifier", idp.Index())
idp.mux.Get("/signin/v1/identifier/", idp.Index())
idp.mux.Get("/signin/v1/identifier/index.html", idp.Index())
idp.mux.Mount("/", gm)
}
// ServeHTTP implements the Service interface.
func (idp IDP) ServeHTTP(w http.ResponseWriter, r *http.Request) {
idp.mux.ServeHTTP(w, r)
}
// Index renders the static html with the
func (idp IDP) Index() http.HandlerFunc {
f, err := idp.assets.Open("/identifier/index.html")
if err != nil {
idp.logger.Fatal().Err(err).Msg("Could not open index template")
}
template, err := ioutil.ReadAll(f)
if err != nil {
idp.logger.Fatal().Err(err).Msg("Could not read index template")
}
if err = f.Close(); err != nil {
idp.logger.Fatal().Err(err).Msg("Could not close body")
}
// TODO add environment variable to make the path prefix configurable
pp := "/signin/v1"
indexHTML := bytes.Replace(template, []byte("__PATH_PREFIX__"), []byte(pp), 1)
nonce := rndm.GenerateRandomString(32)
indexHTML = bytes.Replace(indexHTML, []byte("__CSP_NONCE__"), []byte(nonce), 1)
indexHTML = bytes.Replace(indexHTML, []byte("__PASSWORD_RESET_LINK__"), []byte(idp.config.Service.PasswordResetURI), 1)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
if _, err := w.Write(indexHTML); err != nil {
idp.logger.Error().Err(err).Msg("could not write to response writer")
}
})
}
+23
View File
@@ -0,0 +1,23 @@
package svc
import (
"net/http"
"github.com/owncloud/ocis/ocis-pkg/middleware"
)
// NewTracing returns a service that instruments traces.
func NewTracing(next Service) Service {
return tracing{
next: next,
}
}
type tracing struct {
next Service
}
// ServeHTTP implements the Service interface.
func (t tracing) ServeHTTP(w http.ResponseWriter, r *http.Request) {
middleware.TraceContext(t.next).ServeHTTP(w, r)
}
+23
View File
@@ -0,0 +1,23 @@
package tracing
import (
"github.com/owncloud/ocis/extensions/idp/pkg/config"
pkgtrace "github.com/owncloud/ocis/ocis-pkg/tracing"
"go.opentelemetry.io/otel/trace"
)
var (
// TraceProvider is the global trace provider for the idp service.
TraceProvider = trace.NewNoopTracerProvider()
)
func Configure(cfg *config.Config) error {
var err error
if cfg.Tracing.Enabled {
if TraceProvider, err = pkgtrace.GetTraceProvider(cfg.Tracing.Endpoint, cfg.Tracing.Collector, cfg.Service.Name, cfg.Tracing.Type); err != nil {
return err
}
}
return nil
}