Initial QSfera import

This commit is contained in:
Курнат Андрей
2026-06-07 10:20:04 +03:00
commit 2315f25754
16485 changed files with 4826827 additions and 0 deletions
+54
View File
@@ -0,0 +1,54 @@
package command
import (
"fmt"
"net/http"
"github.com/qsfera/server/pkg/config/configlog"
"github.com/qsfera/server/pkg/log"
"github.com/qsfera/server/services/idm/pkg/config"
"github.com/qsfera/server/services/idm/pkg/config/parser"
"github.com/spf13/cobra"
)
// Health is the entrypoint for the health command.
func Health(cfg *config.Config) *cobra.Command {
return &cobra.Command{
Use: "health",
Short: "check health status",
PreRunE: func(cmd *cobra.Command, args []string) error {
return configlog.ReturnError(parser.ParseConfig(cfg))
},
RunE: func(cmd *cobra.Command, args []string) error {
logger := log.Configure(cfg.Service.Name, cfg.Commons, cfg.LogLevel)
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
},
}
}
+117
View File
@@ -0,0 +1,117 @@
package command
import (
"context"
"errors"
"fmt"
"os"
"syscall"
"time"
"github.com/qsfera/server/pkg/config/configlog"
"github.com/qsfera/server/pkg/log"
"github.com/qsfera/server/services/idm/pkg/config"
"github.com/qsfera/server/services/idm/pkg/config/parser"
"github.com/go-ldap/ldap/v3"
"github.com/libregraph/idm/pkg/ldbbolt"
"github.com/libregraph/idm/server"
"github.com/spf13/cobra"
bolt "go.etcd.io/bbolt"
"golang.org/x/term"
)
// ResetPassword is the entrypoint for the resetpassword command
func ResetPassword(cfg *config.Config) *cobra.Command {
resetPasswordCmd := &cobra.Command{
Use: "resetpassword",
Short: "Reset user password",
PreRunE: func(cmd *cobra.Command, args []string) error {
return configlog.ReturnFatal(parser.ParseConfig(cfg))
},
RunE: func(cmd *cobra.Command, args []string) error {
logger := log.Configure(cfg.Service.Name, cfg.Commons, cfg.LogLevel)
ctx, cancel := context.WithCancel(cmd.Context())
defer cancel()
userNameFlag, _ := cmd.Flags().GetString("user-name")
return resetPassword(ctx, logger, cfg, userNameFlag)
},
}
resetPasswordCmd.Flags().StringP(
"user-name",
"u",
"admin",
"User name",
)
return resetPasswordCmd
}
func resetPassword(_ context.Context, logger log.Logger, cfg *config.Config, userName string) error {
servercfg := server.Config{
Logger: log.LogrusWrap(logger.Logger),
LDAPHandler: "boltdb",
LDAPBaseDN: "o=libregraph-idm",
BoltDBFile: cfg.IDM.DatabasePath,
}
userDN := fmt.Sprintf("uid=%s,ou=users,%s", userName, servercfg.LDAPBaseDN)
fmt.Printf("Resetting password for user '%s'.\n", userDN)
if _, err := os.Stat(servercfg.BoltDBFile); errors.Is(err, os.ErrNotExist) {
fmt.Fprintf(os.Stderr, "IDM database does not exist.\n")
return err
}
newPw, err := getPassword()
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading password: %v\n", err)
return err
}
bdb := &ldbbolt.LdbBolt{}
opts := bolt.Options{
Timeout: 1 * time.Millisecond,
}
if err := bdb.Configure(servercfg.Logger, servercfg.LDAPBaseDN, servercfg.BoltDBFile, &opts); err != nil {
fmt.Fprintf(os.Stderr, "Failed to open database: '%s'. Please stop any running КуСфера idm instance, as this tool requires exclusive access to the database.\n", err)
return err
}
defer bdb.Close()
if err := bdb.Initialize(); err != nil {
return err
}
pwRequest := ldap.NewPasswordModifyRequest(userDN, "", newPw)
if err := bdb.UpdatePassword(pwRequest); err != nil {
fmt.Fprintf(os.Stderr, "Failed to update user password: %v\n", err)
}
fmt.Printf("Password for user '%s' updated.\n", userDN)
return nil
}
func getPassword() (string, error) {
fmt.Print("Enter new password: ")
bytePassword, err := term.ReadPassword(syscall.Stdin)
if err != nil {
return "", err
}
fmt.Println("")
fmt.Print("Re-enter new password: ")
bytePasswordVerify, err := term.ReadPassword(syscall.Stdin)
if err != nil {
return "", err
}
fmt.Println("")
password := string(bytePassword)
passwordVerify := string(bytePasswordVerify)
if password != passwordVerify {
return "", errors.New("Passwords do not match")
}
return password, nil
}
+37
View File
@@ -0,0 +1,37 @@
package command
import (
"os"
"github.com/qsfera/server/pkg/clihelper"
"github.com/qsfera/server/services/idm/pkg/config"
"github.com/spf13/cobra"
)
// GetCommands provides all commands for this service
func GetCommands(cfg *config.Config) []*cobra.Command {
return []*cobra.Command{
// start this service
Server(cfg),
// interaction with this service
ResetPassword(cfg),
// infos about this service
Health(cfg),
Version(cfg),
}
}
// Execute is the entry point for the qsfera idm command.
func Execute(cfg *config.Config) error {
app := clihelper.DefaultApp(&cobra.Command{
Use: "idm",
Short: "Embedded LDAP service for КуСфера",
})
app.AddCommand(GetCommands(cfg)...)
app.SetArgs(os.Args[1:])
return app.ExecuteContext(cfg.Context)
}
+219
View File
@@ -0,0 +1,219 @@
package command
import (
"context"
"encoding/base64"
"errors"
"fmt"
"html/template"
"os"
"os/signal"
"strings"
"github.com/qsfera/server/pkg/config/configlog"
pkgcrypto "github.com/qsfera/server/pkg/crypto"
"github.com/qsfera/server/pkg/log"
"github.com/qsfera/server/pkg/runner"
"github.com/qsfera/server/services/idm"
"github.com/qsfera/server/services/idm/pkg/config"
"github.com/qsfera/server/services/idm/pkg/config/parser"
"github.com/qsfera/server/services/idm/pkg/server/debug"
"github.com/go-ldap/ldif"
"github.com/libregraph/idm/pkg/ldappassword"
"github.com/libregraph/idm/pkg/ldbbolt"
"github.com/libregraph/idm/server"
"github.com/spf13/cobra"
)
// Server is the entrypoint for the server command.
func Server(cfg *config.Config) *cobra.Command {
return &cobra.Command{
Use: "server",
Short: fmt.Sprintf("start the %s service without runtime (unsupervised mode)", cfg.Service.Name),
PreRunE: func(cmd *cobra.Command, args []string) error {
return configlog.ReturnFatal(parser.ParseConfig(cfg))
},
RunE: func(cmd *cobra.Command, args []string) error {
var cancel context.CancelFunc
if cfg.Context == nil {
cfg.Context, cancel = signal.NotifyContext(context.Background(), runner.StopSignals...)
defer cancel()
}
ctx := cfg.Context
logger := log.Configure(cfg.Service.Name, cfg.Commons, cfg.LogLevel)
gr := runner.NewGroup()
{
servercfg := server.Config{
Logger: log.LogrusWrap(logger.Logger),
LDAPHandler: "boltdb",
LDAPSListenAddr: cfg.IDM.LDAPSAddr,
TLSCertFile: cfg.IDM.Cert,
TLSKeyFile: cfg.IDM.Key,
LDAPBaseDN: "o=libregraph-idm",
LDAPAdminDN: "uid=libregraph,ou=sysusers,o=libregraph-idm",
BoltDBFile: cfg.IDM.DatabasePath,
}
if cfg.IDM.LDAPSAddr != "" {
// Generate a self-signing cert if no certificate is present
if err := pkgcrypto.GenCert(cfg.IDM.Cert, cfg.IDM.Key, logger); err != nil {
logger.Fatal().Err(err).Msgf("Could not generate test-certificate")
}
}
if _, err := os.Stat(servercfg.BoltDBFile); errors.Is(err, os.ErrNotExist) {
logger.Debug().Msg("Bootstrapping IDM database")
if err = bootstrap(logger, cfg, servercfg); err != nil {
logger.Error().Err(err).Msg("failed to bootstrap idm database")
}
}
svc, err := server.NewServer(&servercfg)
if err != nil {
return err
}
// we need an additional context for the idm server in order to
// cancel it anytime
svcCtx, svcCancel := context.WithCancel(ctx)
defer svcCancel()
gr.Add(runner.New(cfg.Service.Name+".svc", func() error {
return svc.Serve(svcCtx)
}, func() {
svcCancel()
}))
}
{
debugServer, err := debug.Server(
debug.Logger(logger),
debug.Context(ctx),
debug.Config(cfg),
)
if err != nil {
logger.Info().Err(err).Str("server", "debug").Msg("Failed to initialize server")
return err
}
gr.Add(runner.NewGolangHttpServerRunner(cfg.Service.Name+".debug", debugServer))
}
grResults := gr.Run(ctx)
// return the first non-nil error found in the results
for _, grResult := range grResults {
if grResult.RunnerError != nil {
return grResult.RunnerError
}
}
return nil
},
}
}
func bootstrap(logger log.Logger, cfg *config.Config, srvcfg server.Config) error {
// Hash password if the config does not supply a hash already
var err error
type svcUser struct {
Name string
Password string
ID string
Issuer string
}
serviceUsers := []svcUser{
{
Name: "libregraph",
Password: cfg.ServiceUserPasswords.Idm,
},
{
Name: "idp",
Password: cfg.ServiceUserPasswords.Idp,
},
{
Name: "reva",
Password: cfg.ServiceUserPasswords.Reva,
},
}
if cfg.AdminUserID != "" {
serviceUsers = append(serviceUsers, svcUser{
Name: "admin",
Password: cfg.ServiceUserPasswords.OCAdmin,
ID: cfg.AdminUserID,
Issuer: cfg.DemoUsersIssuerUrl,
})
}
bdb := &ldbbolt.LdbBolt{}
if err := bdb.Configure(srvcfg.Logger, srvcfg.LDAPBaseDN, srvcfg.BoltDBFile, nil); err != nil {
return err
}
defer bdb.Close()
if err := bdb.Initialize(); err != nil {
return err
}
// Prepare the initial Data from template. To be able to set the
// supplied service user passwords
tmpl, err := template.New("baseldif").Parse(idm.BaseLDIF)
if err != nil {
return err
}
for i := range serviceUsers {
if strings.HasPrefix(serviceUsers[i].Password, "$argon2id$") {
// password is alread hashed
serviceUsers[i].Password = "{ARGON2}" + serviceUsers[i].Password
} else {
if serviceUsers[i].Password, err = ldappassword.Hash(serviceUsers[i].Password, "{ARGON2}"); err != nil {
return err
}
}
// We need to treat the hash as binary in the LDIF template to avoid
// go-ldap/ldif to do any fancy escaping
serviceUsers[i].Password = base64.StdEncoding.EncodeToString([]byte(serviceUsers[i].Password))
}
var tmplWriter strings.Builder
err = tmpl.Execute(&tmplWriter, serviceUsers)
if err != nil {
return err
}
bootstrapData := tmplWriter.String()
if cfg.CreateDemoUsers {
demoUsersTmpl, err := template.New("demousers").Parse(idm.DemoUsersLDIF)
if err != nil {
return err
}
var demoUsersWriter strings.Builder
err = demoUsersTmpl.Execute(&demoUsersWriter, cfg.DemoUsersIssuerUrl)
if err != nil {
return err
}
bootstrapData = bootstrapData + "\n" + demoUsersWriter.String()
}
s := strings.NewReader(bootstrapData)
lf := &ldif.LDIF{}
err = ldif.Unmarshal(s, lf)
if err != nil {
return err
}
for _, entry := range lf.AllEntries() {
logger.Debug().Str("dn", entry.DN).Msg("Adding entry")
if err := bdb.EntryPut(entry); err != nil {
return fmt.Errorf("error adding Entry '%s': %w", entry.DN, err)
}
}
return nil
}
@@ -0,0 +1,19 @@
package command
import (
"github.com/qsfera/server/services/idm/pkg/config"
"github.com/spf13/cobra"
)
// Version prints the service versions of all running instances.
func Version(cfg *config.Config) *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "print the version of this binary and the running service instances",
RunE: func(cmd *cobra.Command, args []string) error {
// not implemented
return nil
},
}
}