diff --git a/opencloud/pkg/command/report.go b/opencloud/pkg/command/report.go new file mode 100644 index 0000000000..009b7fba81 --- /dev/null +++ b/opencloud/pkg/command/report.go @@ -0,0 +1,757 @@ +package command + +import ( + "cmp" + "context" + "crypto/tls" + "encoding/csv" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "os" + "slices" + "strconv" + "time" + + "github.com/olekukonko/tablewriter" + "github.com/olekukonko/tablewriter/tw" + "github.com/spf13/cobra" + "gopkg.in/yaml.v3" + + gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1" + libregraph "github.com/opencloud-eu/libre-graph-api-go" + "github.com/opencloud-eu/opencloud/opencloud/pkg/register" + "github.com/opencloud-eu/opencloud/pkg/config" + "github.com/opencloud-eu/opencloud/pkg/config/configlog" + "github.com/opencloud-eu/opencloud/pkg/config/parser" + mregistry "github.com/opencloud-eu/opencloud/pkg/registry" + gatewayparser "github.com/opencloud-eu/opencloud/services/gateway/pkg/config/parser" + graphparser "github.com/opencloud-eu/opencloud/services/graph/pkg/config/parser" + revactx "github.com/opencloud-eu/reva/v2/pkg/ctx" + "github.com/opencloud-eu/reva/v2/pkg/rgrpc/todo/pool" + "github.com/opencloud-eu/reva/v2/pkg/utils" +) + +const ( + _reportOutputFlagName = "output" + _reportDaysFlagName = "days" + _reportSignInFlagName = "with-sign-in" + _reportInsecureFlagName = "insecure" + _reportTimeoutFlagName = "timeout" + + // _reportDefaultDays is the default sign-in window in days. + _reportDefaultDays = 31 + + // _reportNoRole is the bucket for users without any assigned role. + _reportNoRole = "(no role assigned)" + + // _reportDefaultTimeout caps the whole report run by default. The graph API + // resolves the role assignments per user, so the run grows with the number + // of users: a minute covers roughly ten thousand of them, and a larger + // instance can raise it with --timeout. + _reportDefaultTimeout = 5 * time.Minute + + _reportOutputTable = "table" + _reportOutputJSON = "json" + _reportOutputCSV = "csv" + _reportOutputYAML = "yaml" +) + +// roleCount is the number of users sharing one assigned role. +type roleCount struct { + Role string `json:"role" yaml:"role"` + // Users counts every user holding the role, whether or not a sign-in is + // known for them. + Users int `json:"users" yaml:"users"` + // SignedIn counts the subset that signed in within the reported window. It + // is nil when the instance does not record sign-ins at all, to tell "not + // available" apart from "nobody signed in". + SignedIn *int `json:"signedIn" yaml:"signedIn"` +} + +// userReport is the result of the report command. +type userReport struct { + GeneratedAt time.Time `json:"generatedAt" yaml:"generatedAt"` + Days int `json:"days" yaml:"days"` + ActiveSince time.Time `json:"activeSince" yaml:"activeSince"` + TotalUsers int `json:"totalUsers" yaml:"totalUsers"` + // ActiveUsers is the number of users that signed in within the reported + // window. Like roleCount.SignedIn it is nil when the instance does not + // record sign-ins at all. + ActiveUsers *int `json:"activeUsers" yaml:"activeUsers"` + // UsersWithSignInData is the number of users that have a recorded sign-in + // at all, regardless of the reported window. It is 0 when the deployment + // does not store sign-in timestamps. + UsersWithSignInData int `json:"usersWithSignInData" yaml:"usersWithSignInData"` + Roles []roleCount `json:"roles" yaml:"roles"` + // SignInReported tells the renderers that the sign-in window was reported. + // Without it the sign-in fields are meaningless and are left out entirely. + SignInReported bool `json:"-" yaml:"-"` +} + +// plainRoleCount is a roleCount without its sign-in column. +type plainRoleCount struct { + Role string `json:"role" yaml:"role"` + Users int `json:"users" yaml:"users"` +} + +// plainUserReport is a userReport without any sign-in data, used when the +// sign-in window is skipped. The sign-in fields are dropped rather than +// reported as null, because nothing was looked at in the first place. +type plainUserReport struct { + GeneratedAt time.Time `json:"generatedAt" yaml:"generatedAt"` + TotalUsers int `json:"totalUsers" yaml:"totalUsers"` + Roles []plainRoleCount `json:"roles" yaml:"roles"` +} + +// plain reduces the report to its user counts per role. +func (r userReport) plain() plainUserReport { + roles := make([]plainRoleCount, 0, len(r.Roles)) + for _, role := range r.Roles { + roles = append(roles, plainRoleCount{Role: role.Role, Users: role.Users}) + } + return plainUserReport{ + GeneratedAt: r.GeneratedAt, + TotalUsers: r.TotalUsers, + Roles: roles, + } +} + +// reportOptions holds the settings a report run takes from the command line. +type reportOptions struct { + // days is the width of the sign-in window, only used with withSignIn. + days int + // withSignIn adds the sign-in window to the report. Off by default: the + // data only exists on a writable LDAP backend. + withSignIn bool + // insecure skips the TLS certificate check against the graph service, for + // deployments serving the generated self-signed certificate. + insecure bool + // timeout caps the whole run, the context and the HTTP client alike. + timeout time.Duration +} + +// ReportCommand is the entrypoint for the report command. +func ReportCommand(cfg *config.Config) *cobra.Command { + reportCmd := &cobra.Command{ + Use: "report", + Short: "report the users of this instance grouped by their assigned role", + Long: "Report the users of OpenCloud grouped by their assigned role.\n\n" + + "By default every user is counted once and the report is a plain user\n" + + "count per role.\n\n" + + "Pass --with-sign-in to additionally report, per role, how many of its\n" + + "users signed in successfully within the last --days days. Users whose\n" + + "sign-in is unknown still count towards their role. OpenCloud stores the\n" + + "last sign-in on the user entry in LDAP, so this needs an LDAP identity\n" + + "backend that OpenCloud may write to and is refused otherwise.\n" + + "The data is read from the libregraph API of a running OpenCloud instance,\n" + + "so the instance needs to be up while the report is generated.", + GroupID: CommandGroupServer, + PreRunE: func(cmd *cobra.Command, args []string) error { + // Parse base config + if err := parser.ParseConfig(cfg, true); err != nil { + return configlog.ReturnError(err) + } + + // Parse graph config, the report talks to the graph service + cfg.Graph.Commons = cfg.Commons + if err := graphparser.ParseConfig(cfg.Graph); err != nil { + return configlog.ReturnError(err) + } + + // Parse gateway config, it carries the address the report falls back + // to when the service registry holds no entry for the gateway + cfg.Gateway.Commons = cfg.Commons + return configlog.ReturnError(gatewayparser.ParseConfig(cfg.Gateway)) + }, + RunE: func(cmd *cobra.Command, args []string) error { + days, err := cmd.Flags().GetInt(_reportDaysFlagName) + if err != nil { + return err + } + withSignIn, err := cmd.Flags().GetBool(_reportSignInFlagName) + if err != nil { + return err + } + if !withSignIn && cmd.Flags().Changed(_reportDaysFlagName) { + return fmt.Errorf("--%s only applies together with --%s", + _reportDaysFlagName, _reportSignInFlagName) + } + if withSignIn { + if reason := signInUnavailable(cfg); reason != "" { + return fmt.Errorf("--%s is not available on this instance: %s", + _reportSignInFlagName, reason) + } + if days < 1 { + return fmt.Errorf("--%s must be at least 1", _reportDaysFlagName) + } + } + + format, err := cmd.Flags().GetString(_reportOutputFlagName) + if err != nil { + return err + } + if !slices.Contains([]string{_reportOutputTable, _reportOutputJSON, _reportOutputCSV, _reportOutputYAML}, format) { + return fmt.Errorf("unknown output format %q, supported formats are: %s, %s, %s, %s", + format, _reportOutputTable, _reportOutputJSON, _reportOutputCSV, _reportOutputYAML) + } + + insecure, err := cmd.Flags().GetBool(_reportInsecureFlagName) + if err != nil { + return err + } + + timeout, err := cmd.Flags().GetDuration(_reportTimeoutFlagName) + if err != nil { + return err + } + if timeout <= 0 { + return fmt.Errorf("--%s must be positive", _reportTimeoutFlagName) + } + + ctx, cancel := context.WithTimeout(cmd.Context(), timeout) + defer cancel() + + report, err := userRoleReport(ctx, cfg, reportOptions{ + days: days, + withSignIn: withSignIn, + insecure: insecure, + timeout: timeout, + }) + if err != nil { + return err + } + + return renderUserReport(os.Stdout, report, format) + }, + } + + reportCmd.Flags().IntP(_reportDaysFlagName, "d", _reportDefaultDays, + "window in days for counting users who signed in successfully") + reportCmd.Flags().StringP(_reportOutputFlagName, "o", _reportOutputTable, + fmt.Sprintf("output format, one of: %s, %s, %s, %s", + _reportOutputTable, _reportOutputJSON, _reportOutputCSV, _reportOutputYAML)) + reportCmd.Flags().Bool(_reportSignInFlagName, false, + "additionally report how many users per role signed in within the last --days days. Needs a writable LDAP identity backend") + reportCmd.Flags().DurationP(_reportTimeoutFlagName, "t", _reportDefaultTimeout, + "time budget for the whole report run, e.g. 10m. Raise it on instances with very many users") + reportCmd.Flags().Bool(_reportInsecureFlagName, false, + "do not verify the TLS certificate of the graph service, e.g. when it serves a generated self-signed certificate") + + return reportCmd +} + +func init() { + register.AddCommand(ReportCommand) +} + +// signInUnavailable reports why this instance cannot report sign-ins, or an +// empty string when it can. OpenCloud stores the last successful sign-in as an +// attribute on the user entry, so it needs an LDAP identity backend that the +// graph service may write to. Without that no timestamp is ever recorded and +// the sign-in counts would be meaningless rather than merely empty. +func signInUnavailable(cfg *config.Config) string { + if backend := cfg.Graph.Identity.Backend; backend != "ldap" { + return fmt.Sprintf("the %q identity backend does not record sign-ins", backend) + } + if !cfg.Graph.Identity.LDAP.WriteEnabled { + return "the LDAP identity backend is read-only, see OC_LDAP_SERVER_WRITE_ENABLED, so no sign-in is ever recorded" + } + return "" +} + +// userRoleReport collects all users from the libregraph API and groups them by +// their assigned role. By default the result is a plain user count per role. +// With withSignIn it additionally reports, per role, how many of its users +// signed in within the last `days` days. +func userRoleReport(ctx context.Context, cfg *config.Config, opts reportOptions) (userReport, error) { + client, err := newLibregraphServiceAccountClient(ctx, cfg, opts) + if err != nil { + return userReport{}, err + } + + roleNames, err := appRoleNames(ctx, client) + if err != nil { + return userReport{}, err + } + + users, err := listUsersWithRoleAssignments(ctx, client) + if err != nil { + return userReport{}, err + } + + now := time.Now().UTC() + // a nil window tells countUsersByRole to not look at sign-ins at all + var activeSince *time.Time + if opts.withSignIn { + since := now.AddDate(0, 0, -opts.days) + activeSince = &since + } + roles, activeUsers, withSignInData := countUsersByRole(users, roleNames, activeSince) + + report := userReport{ + GeneratedAt: now, + TotalUsers: len(users), + Roles: roles, + SignInReported: opts.withSignIn, + } + if activeSince != nil { + report.Days = opts.days + report.ActiveSince = *activeSince + report.ActiveUsers = activeUsers + report.UsersWithSignInData = withSignInData + } + return report, nil +} + +// countUsersByRole groups every user by the display names of their assigned +// roles, counting for each role both its total number of users and the subset +// that signed in at or after activeSince. Users whose sign-in is unknown are +// still counted towards their role. It returns the counts ordered by size, the +// number of users that signed in within the window and the number of users +// that have a recorded sign-in at all. Users with multiple roles are counted +// once per role. +// +// When the instance holds no sign-in data at all the sign-in counts are +// returned as nil rather than 0, so that callers can report them as not +// available instead of claiming nobody signed in. A nil activeSince skips the +// sign-in accounting altogether and only groups the users by role. +func countUsersByRole(users []libregraph.User, roleNames map[string]string, activeSince *time.Time) ([]roleCount, *int, int) { + totals := make(map[string]int, len(roleNames)+1) + signedIn := make(map[string]int, len(roleNames)+1) + activeUsers := 0 + withSignInData := 0 + for _, u := range users { + active := false + if activeSince != nil { + signInActivity := u.GetSignInActivity() + lastSignIn, hasSignIn := signInActivity.GetLastSuccessfulSignInDateTimeOk() + if hasSignIn { + withSignInData++ + } + active = hasSignIn && !lastSignIn.Before(*activeSince) + if active { + activeUsers++ + } + } + + for _, name := range assignedRoleNames(u, roleNames) { + totals[name]++ + if active { + signedIn[name]++ + } + } + } + + // without a single recorded sign-in we cannot tell an inactive user from + // one whose sign-in was never stored, and without a window we never looked + signInKnown := activeSince != nil && (withSignInData > 0 || len(users) == 0) + + roles := make([]roleCount, 0, len(totals)) + for name, total := range totals { + roles = append(roles, roleCount{ + Role: name, + Users: total, + SignedIn: optionalCount(signedIn[name], signInKnown), + }) + } + // biggest role first, alphabetically for equal counts + slices.SortFunc(roles, func(a, b roleCount) int { + if c := cmp.Compare(b.Users, a.Users); c != 0 { + return c + } + return cmp.Compare(a.Role, b.Role) + }) + + return roles, optionalCount(activeUsers, signInKnown), withSignInData +} + +// optionalCount returns a pointer to count, or nil when the count is not known. +func optionalCount(count int, known bool) *int { + if !known { + return nil + } + return &count +} + +// assignedRoleNames resolves the roles of a user to their display names. Users +// without any assignment get a bucket of their own, so that they still show up +// in the report. +func assignedRoleNames(user libregraph.User, roleNames map[string]string) []string { + assignments := user.GetAppRoleAssignments() + if len(assignments) == 0 { + return []string{_reportNoRole} + } + + names := make([]string, 0, len(assignments)) + for _, a := range assignments { + name, ok := roleNames[a.GetAppRoleId()] + if !ok { + // an assignment pointing to a role the application no longer + // exposes, report the raw id so it doesn't vanish silently + name = a.GetAppRoleId() + } + names = append(names, name) + } + return names +} + +// newLibregraphServiceAccountClient builds a libregraph client authenticated as +// the configured service account. The graph endpoint is looked up in the +// service registry, so this only works against a running instance. +func newLibregraphServiceAccountClient(ctx context.Context, cfg *config.Config, opts reportOptions) (*libregraph.APIClient, error) { + // Initialize registry to make service lookup work + reg := mregistry.GetRegistry() + + gatewayClient, err := selectGateway(cfg) + if err != nil { + return nil, err + } + + token, err := utils.GetServiceUserToken( + ctx, + gatewayClient, + cfg.Graph.ServiceAccount.ServiceAccountID, + cfg.Graph.ServiceAccount.ServiceAccountSecret, + ) + if err != nil { + return nil, fmt.Errorf("could not authenticate the service account: %w", err) + } + + serviceName := cfg.Graph.HTTP.Namespace + "." + cfg.Graph.Service.Name + var baseURL string + // A lookup error means the registry holds no entry, which is not fatal: + // the fallback below covers it. + if services, err := reg.GetService(serviceName); err == nil { + for _, s := range services { + for _, n := range s.Nodes { + baseURL = fmt.Sprintf("%s://%s%s", nodeProtocol(n.Metadata), n.Address, cfg.Graph.HTTP.Root) + break + } + if baseURL != "" { + break + } + } + } + if baseURL == "" { + baseURL = configuredGraphURL(cfg) + } + if baseURL == "" { + return nil, fmt.Errorf("could not find the '%s' service, is OpenCloud running?", serviceName) + } + + lgconf := libregraph.NewConfiguration() + lgconf.Servers = libregraph.ServerConfigurations{{URL: baseURL}} + lgconf.DefaultHeader = map[string]string{revactx.TokenHeader: token} + lgconf.HTTPClient = newGraphHTTPClient(opts) + + return libregraph.NewAPIClient(lgconf), nil +} + +// newGraphHTTPClient builds the HTTP client for the graph API. It requires TLS +// 1.2 or newer for an encrypted connection, and only skips the certificate +// check when --insecure asked for it. The default transport is cloned rather +// than replaced, so that proxy support, HTTP/2 and connection pooling stay as +// they are. +func newGraphHTTPClient(opts reportOptions) *http.Client { + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.TLSClientConfig = &tls.Config{ + MinVersion: tls.VersionTLS12, + // #nosec G402 -- off unless the admin passes --insecure + InsecureSkipVerify: opts.insecure, //nolint:gosec // opt-in via --insecure + } + return &http.Client{ + Timeout: opts.timeout, + Transport: transport, + } +} + +// selectGateway returns a CS3 gateway client. It first tries the configured +// reva address, which is a service registry name by default, and falls back to +// dialling the configured gateway address directly over dns:///. That covers a +// deployment running the services with MICRO_REGISTRY=memory, where a separate +// process finds an empty registry but the gateway still listens next to it. +func selectGateway(cfg *config.Config) (gateway.GatewayAPIClient, error) { + addresses := []string{cfg.Graph.Reva.Address} + if fallback := configuredGatewayAddress(cfg); fallback != "" { + addresses = append(addresses, fallback) + } + + var lastErr error + for _, address := range addresses { + selector, err := pool.GatewaySelector(address) + if err != nil { + lastErr = err + continue + } + client, err := selector.Next() + if err != nil { + lastErr = err + continue + } + return client, nil + } + return nil, lastErr +} + +// configuredGatewayAddress renders the configured gateway bind address as a +// dns:/// target, so that it is dialled directly instead of being looked up in +// the service registry. A wildcard bind address is rewritten to loopback, +// because the report runs next to the gateway it talks to. +func configuredGatewayAddress(cfg *config.Config) string { + if cfg.Gateway == nil || cfg.Gateway.GRPC.Addr == "" { + return "" + } + host, port, err := net.SplitHostPort(cfg.Gateway.GRPC.Addr) + if err != nil { + return "" + } + switch host { + case "", "0.0.0.0", "::", "[::]": + host = "127.0.0.1" + } + return "dns:///" + net.JoinHostPort(host, port) +} + +// configuredGraphURL builds the graph base URL from the local configuration. +// It is the fallback when the service registry holds no entry, which is the +// case on a deployment that runs the services with MICRO_REGISTRY=memory and +// discovers them through Kubernetes instead. The report has to run next to the +// services anyway, so the configured address of the local graph service is the +// right answer rather than a guess. +func configuredGraphURL(cfg *config.Config) string { + if cfg.Graph.HTTP.Addr == "" { + return "" + } + scheme := "http" + if cfg.Commons != nil && cfg.Commons.HTTPServiceTLS.Enabled { + scheme = "https" + } + return fmt.Sprintf("%s://%s%s", scheme, cfg.Graph.HTTP.Addr, cfg.Graph.HTTP.Root) +} + +// nodeProtocol resolves the URL scheme to talk to a registry node with. The +// registry reports "http" for every HTTP service and signals TLS separately +// through the use_tls metadata, so that flag decides, the same way the proxy +// router resolves it. +func nodeProtocol(metadata map[string]string) string { + if metadata["use_tls"] == "true" { + return "https" + } + if protocol := metadata["protocol"]; protocol != "" { + return protocol + } + return "http" +} + +// appRoleNames maps the app role ids of the OpenCloud application to their +// display names, e.g. "Admin" or "Space Admin". +func appRoleNames(ctx context.Context, client *libregraph.APIClient) (map[string]string, error) { + applications, resp, err := client.ApplicationsApi.ListApplications(ctx).Execute() + if resp != nil { + defer resp.Body.Close() + } + if err != nil { + return nil, fmt.Errorf("could not list applications: %w", err) + } + + names := map[string]string{} + for _, application := range applications.GetValue() { + for _, role := range application.GetAppRoles() { + name := role.GetDisplayName() + if name == "" { + name = role.GetId() + } + names[role.GetId()] = name + } + } + return names, nil +} + +// listUsersWithRoleAssignments returns all users including their app role assignments. +func listUsersWithRoleAssignments(ctx context.Context, client *libregraph.APIClient) ([]libregraph.User, error) { + users, resp, err := client.UsersApi.ListUsers(ctx).Expand([]string{"appRoleAssignments"}).Execute() + if resp != nil { + defer resp.Body.Close() + } + if err != nil { + return nil, fmt.Errorf("could not list users: %w", err) + } + return users.GetValue(), nil +} + +// renderUserReport writes the report in the requested output format. +func renderUserReport(w io.Writer, report userReport, format string) error { + switch format { + case _reportOutputJSON: + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + if !report.SignInReported { + return enc.Encode(report.plain()) + } + return enc.Encode(report) + case _reportOutputYAML: + enc := yaml.NewEncoder(w) + defer enc.Close() + if !report.SignInReported { + return enc.Encode(report.plain()) + } + return enc.Encode(report) + case _reportOutputCSV: + if !report.SignInReported { + return renderPlainCSV(w, report) + } + cw := csv.NewWriter(w) + if err := cw.Write([]string{ + "days", "activeSince", "totalUsers", "activeUsers", "usersWithSignInData", + "role", "users", "signedIn", + }); err != nil { + return err + } + // the report context is repeated per row so that a single flat table + // carries the totals as well, even when there is no role at all + prefix := []string{ + strconv.Itoa(report.Days), + report.ActiveSince.Format(time.RFC3339), + strconv.Itoa(report.TotalUsers), + csvCount(report.ActiveUsers), + strconv.Itoa(report.UsersWithSignInData), + } + if len(report.Roles) == 0 { + // a placeholder row keeps the totals readable for a consumer that + // only looks at the rows; its sign-in cell follows availability + noSignedIn := csvCount(optionalCount(0, report.ActiveUsers != nil)) + if err := cw.Write(slices.Concat(prefix, []string{"", "0", noSignedIn})); err != nil { + return err + } + } + for _, r := range report.Roles { + row := slices.Concat(prefix, []string{r.Role, strconv.Itoa(r.Users), csvCount(r.SignedIn)}) + if err := cw.Write(row); err != nil { + return err + } + } + cw.Flush() + return cw.Error() + default: + if !report.SignInReported { + return renderPlainTable(w, report) + } + fmt.Fprintf(w, "Sign-in window: last %s (since %s)\n\n", + pluralDays(report.Days), report.ActiveSince.Format(time.RFC3339)) + + signedInLabel := "Signed in within the last " + pluralDays(report.Days) + totalLabel := "Users in total:" + activeLabel := signedInLabel + ":" + knownLabel := "Users with a recorded sign-in:" + labelWidth := max(len(totalLabel), len(activeLabel), len(knownLabel)) + fmt.Fprintf(w, "%-*s %d\n", labelWidth, totalLabel, report.TotalUsers) + fmt.Fprintf(w, "%-*s %s\n", labelWidth, activeLabel, tableCount(report.ActiveUsers)) + fmt.Fprintf(w, "%-*s %d\n\n", labelWidth, knownLabel, report.UsersWithSignInData) + + table := tablewriter.NewTable(w, tablewriter.WithConfig(tablewriter.Config{ + Header: tw.CellConfig{ + Formatting: tw.CellFormatting{AutoFormat: tw.Off}, + }, + Row: tw.CellConfig{ + Alignment: tw.CellAlignment{ + PerColumn: []tw.Align{tw.AlignLeft, tw.AlignRight, tw.AlignRight}, + }, + }, + })) + table.Header([]string{"Role", "Users", signedInLabel}) + for _, r := range report.Roles { + row := []string{r.Role, strconv.Itoa(r.Users), tableCount(r.SignedIn)} + if err := table.Append(row); err != nil { + return err + } + } + if err := table.Render(); err != nil { + return err + } + + if report.TotalUsers > 0 && report.UsersWithSignInData == 0 { + fmt.Fprint(w, "\nWarning: not a single user has a recorded sign-in, so the sign-in\n"+ + "counts are reported as N/A rather than 0. The identity backend accepts\n"+ + "the write, so either nobody has signed in since sign-in recording was\n"+ + "switched on, or the directory does not hold the OpenCloud LDAP schema.\n") + } + return nil + } +} + +// renderPlainCSV writes the user counts per role as csv, without any of the +// sign-in columns. +func renderPlainCSV(w io.Writer, report userReport) error { + cw := csv.NewWriter(w) + if err := cw.Write([]string{"totalUsers", "role", "users"}); err != nil { + return err + } + total := strconv.Itoa(report.TotalUsers) + if len(report.Roles) == 0 { + // a placeholder row keeps the total readable for a consumer that only + // looks at the rows + if err := cw.Write([]string{total, "", "0"}); err != nil { + return err + } + } + for _, r := range report.Roles { + if err := cw.Write([]string{total, r.Role, strconv.Itoa(r.Users)}); err != nil { + return err + } + } + cw.Flush() + return cw.Error() +} + +// renderPlainTable writes the user counts per role as a table, without the +// sign-in column, the sign-in totals and the warning about missing sign-ins. +func renderPlainTable(w io.Writer, report userReport) error { + fmt.Fprintf(w, "Users in total: %d\n\n", report.TotalUsers) + + table := tablewriter.NewTable(w, tablewriter.WithConfig(tablewriter.Config{ + Header: tw.CellConfig{ + Formatting: tw.CellFormatting{AutoFormat: tw.Off}, + }, + Row: tw.CellConfig{ + Alignment: tw.CellAlignment{ + PerColumn: []tw.Align{tw.AlignLeft, tw.AlignRight}, + }, + }, + })) + table.Header([]string{"Role", "Users"}) + for _, r := range report.Roles { + if err := table.Append([]string{r.Role, strconv.Itoa(r.Users)}); err != nil { + return err + } + } + return table.Render() +} + +// tableCount renders a sign-in count for human readable output, spelling out +// that it is not available rather than showing a misleading 0. +func tableCount(count *int) string { + if count == nil { + return "N/A" + } + return strconv.Itoa(*count) +} + +// csvCount renders a sign-in count for csv output, leaving the cell empty when +// the count is not available. +func csvCount(count *int) string { + if count == nil { + return "" + } + return strconv.Itoa(*count) +} + +// pluralDays renders a day count for human readable output. +func pluralDays(days int) string { + if days == 1 { + return "1 day" + } + return strconv.Itoa(days) + " days" +} diff --git a/opencloud/pkg/command/report_test.go b/opencloud/pkg/command/report_test.go new file mode 100644 index 0000000000..a3abd8e5de --- /dev/null +++ b/opencloud/pkg/command/report_test.go @@ -0,0 +1,795 @@ +package command + +import ( + "bytes" + "crypto/tls" + "net/http" + "regexp" + "strings" + "testing" + "time" + + libregraph "github.com/opencloud-eu/libre-graph-api-go" + "github.com/opencloud-eu/opencloud/pkg/config" + "github.com/opencloud-eu/opencloud/pkg/shared" + gatewayconfig "github.com/opencloud-eu/opencloud/services/gateway/pkg/config" + graphconfig "github.com/opencloud-eu/opencloud/services/graph/pkg/config" +) + +const ( + adminRoleID = "1ecb83a2-d7b2-4b67-9d81-3d3e4f8a9b0c" + userRoleID = "d7beeea8-8ff4-4b0e-9d7e-1c1d3c3bd0e1" + spaceAdminRoleID = "9f4f8f3f-3e34-4a1a-9a7e-26f1b0a0a3b1" +) + +func testRoleNames() map[string]string { + return map[string]string{ + adminRoleID: "Admin", + userRoleID: "User", + spaceAdminRoleID: "Space Admin", + } +} + +func countPtr(c int) *int { + return &c +} + +// testUser builds a user with the given last successful sign-in and role +// assignments. A nil lastSignIn means the user never signed in. +func testUser(name string, lastSignIn *time.Time, roleIDs ...string) libregraph.User { + u := libregraph.User{DisplayName: name, OnPremisesSamAccountName: name} + if lastSignIn != nil { + u.SetSignInActivity(libregraph.SignInActivity{LastSuccessfulSignInDateTime: lastSignIn}) + } + for _, id := range roleIDs { + u.AppRoleAssignments = append(u.AppRoleAssignments, libregraph.AppRoleAssignment{AppRoleId: id}) + } + return u +} + +func TestCountUsersByRole(t *testing.T) { + activeSince := time.Date(2026, 9, 8, 0, 0, 0, 0, time.UTC) + + recent := activeSince.Add(24 * time.Hour) + onCutoff := activeSince + stale := activeSince.Add(-time.Second) + + testCases := []struct { + name string + users []libregraph.User + expectedRoles []roleCount + expectedActive *int + expectedWithSignInfo int + }{ + { + name: "no users", + users: nil, + expectedRoles: []roleCount{}, + expectedActive: countPtr(0), + expectedWithSignInfo: 0, + }, + { + name: "roles are ordered by count, then by name", + users: []libregraph.User{ + testUser("einstein", &recent, userRoleID), + testUser("marie", &recent, userRoleID), + testUser("moss", &recent, spaceAdminRoleID), + testUser("admin", &recent, adminRoleID), + }, + expectedRoles: []roleCount{ + {Role: "User", Users: 2, SignedIn: countPtr(2)}, + {Role: "Admin", Users: 1, SignedIn: countPtr(1)}, + {Role: "Space Admin", Users: 1, SignedIn: countPtr(1)}, + }, + expectedActive: countPtr(4), + expectedWithSignInfo: 4, + }, + { + name: "users that never signed in still count towards their role", + users: []libregraph.User{ + testUser("einstein", &recent, userRoleID), + testUser("marie", nil, userRoleID), + }, + expectedRoles: []roleCount{{Role: "User", Users: 2, SignedIn: countPtr(1)}}, + expectedActive: countPtr(1), + expectedWithSignInfo: 1, + }, + { + name: "users outside the window still count towards their role", + users: []libregraph.User{ + testUser("einstein", &onCutoff, userRoleID), + testUser("marie", &stale, userRoleID), + }, + expectedRoles: []roleCount{{Role: "User", Users: 2, SignedIn: countPtr(1)}}, + expectedActive: countPtr(1), + expectedWithSignInfo: 2, + }, + { + name: "sign-in counts are unknown when no sign-in was ever recorded", + users: []libregraph.User{ + testUser("einstein", nil, userRoleID), + testUser("admin", nil, adminRoleID), + }, + expectedRoles: []roleCount{ + {Role: "Admin", Users: 1, SignedIn: nil}, + {Role: "User", Users: 1, SignedIn: nil}, + }, + expectedActive: nil, + expectedWithSignInfo: 0, + }, + { + name: "users without a role land in their own bucket", + users: []libregraph.User{testUser("einstein", &recent)}, + expectedRoles: []roleCount{{Role: _reportNoRole, Users: 1, SignedIn: countPtr(1)}}, + expectedActive: countPtr(1), + expectedWithSignInfo: 1, + }, + { + name: "users with multiple roles are counted for each of them", + users: []libregraph.User{testUser("einstein", &recent, adminRoleID, spaceAdminRoleID)}, + expectedRoles: []roleCount{ + {Role: "Admin", Users: 1, SignedIn: countPtr(1)}, + {Role: "Space Admin", Users: 1, SignedIn: countPtr(1)}, + }, + expectedActive: countPtr(1), + expectedWithSignInfo: 1, + }, + { + name: "unknown roles are reported by their id", + users: []libregraph.User{testUser("einstein", &recent, "some-unknown-role-id")}, + expectedRoles: []roleCount{{Role: "some-unknown-role-id", Users: 1, SignedIn: countPtr(1)}}, + expectedActive: countPtr(1), + expectedWithSignInfo: 1, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + roles, active, withSignInfo := countUsersByRole(tc.users, testRoleNames(), &activeSince) + + if tableCount(active) != tableCount(tc.expectedActive) { + t.Errorf("expected %s active users, got %s", tableCount(tc.expectedActive), tableCount(active)) + } + if withSignInfo != tc.expectedWithSignInfo { + t.Errorf("expected %d users with sign-in data, got %d", tc.expectedWithSignInfo, withSignInfo) + } + if len(roles) != len(tc.expectedRoles) { + t.Fatalf("expected %d roles, got %d", len(tc.expectedRoles), len(roles)) + } + for i, expected := range tc.expectedRoles { + got := roles[i] + if got.Role != expected.Role || got.Users != expected.Users || + tableCount(got.SignedIn) != tableCount(expected.SignedIn) { + t.Errorf("role %d: expected %s/%d/%s, got %s/%d/%s", + i, expected.Role, expected.Users, tableCount(expected.SignedIn), + got.Role, got.Users, tableCount(got.SignedIn)) + } + } + }) + } +} + +func TestRenderUserReport(t *testing.T) { + report := userReport{ + GeneratedAt: time.Date(2026, 10, 9, 12, 0, 0, 0, time.UTC), + Days: 31, + ActiveSince: time.Date(2026, 9, 8, 12, 0, 0, 0, time.UTC), + TotalUsers: 5, + ActiveUsers: countPtr(3), + UsersWithSignInData: 4, + SignInReported: true, + Roles: []roleCount{ + {Role: "User", Users: 3, SignedIn: countPtr(2)}, + {Role: "Admin", Users: 1, SignedIn: countPtr(1)}, + }, + } + + testCases := []struct { + format string + expected []string + }{ + { + format: _reportOutputTable, + expected: []string{ + "Sign-in window: last 31 days (since 2026-09-08T12:00:00Z)", + "Users in total: 5", + "Signed in within the last 31 days: 3", + "Users with a recorded sign-in: 4", + "Role", "Users", "Admin", "User", + }, + }, + { + format: _reportOutputJSON, + expected: []string{ + `"activeSince": "2026-09-08T12:00:00Z"`, + `"totalUsers": 5`, + `"activeUsers": 3`, + `"usersWithSignInData": 4`, + `"role": "Admin"`, + `"users": 1`, + `"signedIn": 2`, + }, + }, + { + format: _reportOutputCSV, + expected: []string{ + "days,activeSince,totalUsers,activeUsers,usersWithSignInData,role,users,signedIn\n" + + "31,2026-09-08T12:00:00Z,5,3,4,User,3,2\n" + + "31,2026-09-08T12:00:00Z,5,3,4,Admin,1,1\n", + }, + }, + { + format: _reportOutputYAML, + expected: []string{ + "days: 31", "totalUsers: 5", "activeUsers: 3", "usersWithSignInData: 4", + "- role: User", "users: 3", "signedIn: 2", + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.format, func(t *testing.T) { + var buf bytes.Buffer + if err := renderUserReport(&buf, report, tc.format); err != nil { + t.Fatalf("unexpected error: %v", err) + } + // collapse the padding the table format uses to align its labels + actual := regexp.MustCompile(` +`).ReplaceAllString(buf.String(), " ") + for _, expected := range tc.expected { + if !strings.Contains(actual, expected) { + t.Errorf("expected output to contain %q, got:\n%s", expected, buf.String()) + } + } + }) + } +} + +// TestRenderUserReportNobodySignedInRecently makes sure the role grouping is +// still reported in full when nobody signed in within the reported window, and +// that a genuine 0 stays a 0. +func TestRenderUserReportNobodySignedInRecently(t *testing.T) { + report := userReport{ + GeneratedAt: time.Date(2026, 10, 9, 12, 0, 0, 0, time.UTC), + Days: 1, + ActiveSince: time.Date(2026, 10, 8, 12, 0, 0, 0, time.UTC), + TotalUsers: 5, + ActiveUsers: countPtr(0), + UsersWithSignInData: 5, + SignInReported: true, + Roles: []roleCount{ + {Role: "User", Users: 4, SignedIn: countPtr(0)}, + {Role: "Admin", Users: 1, SignedIn: countPtr(0)}, + }, + } + + testCases := []struct { + format string + expected []string + }{ + { + format: _reportOutputTable, + expected: []string{"Signed in within the last 1 day: 0", "User", "Admin"}, + }, + {format: _reportOutputJSON, expected: []string{`"activeUsers": 0`, `"users": 4`}}, + {format: _reportOutputYAML, expected: []string{"activeUsers: 0", "users: 4"}}, + { + format: _reportOutputCSV, + expected: []string{ + "days,activeSince,totalUsers,activeUsers,usersWithSignInData,role,users,signedIn\n" + + "1,2026-10-08T12:00:00Z,5,0,5,User,4,0\n" + + "1,2026-10-08T12:00:00Z,5,0,5,Admin,1,0\n", + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.format, func(t *testing.T) { + var buf bytes.Buffer + if err := renderUserReport(&buf, report, tc.format); err != nil { + t.Fatalf("unexpected error: %v", err) + } + actual := regexp.MustCompile(` +`).ReplaceAllString(buf.String(), " ") + for _, expected := range tc.expected { + if !strings.Contains(actual, expected) { + t.Errorf("expected output to contain %q, got:\n%s", expected, buf.String()) + } + } + if strings.Contains(actual, "N/A") { + t.Errorf("did not expect an N/A count, got:\n%s", buf.String()) + } + if strings.Contains(actual, "Warning:") { + t.Errorf("did not expect a warning, got:\n%s", buf.String()) + } + }) + } +} + +// TestRenderUserReportWithoutUsers makes sure the csv output keeps carrying the +// report context when there is not a single user to group. +func TestRenderUserReportWithoutUsers(t *testing.T) { + report := userReport{ + GeneratedAt: time.Date(2026, 10, 9, 12, 0, 0, 0, time.UTC), + Days: 31, + ActiveSince: time.Date(2026, 9, 8, 12, 0, 0, 0, time.UTC), + ActiveUsers: countPtr(0), + SignInReported: true, + Roles: []roleCount{}, + } + + var buf bytes.Buffer + if err := renderUserReport(&buf, report, _reportOutputCSV); err != nil { + t.Fatalf("unexpected error: %v", err) + } + expected := "days,activeSince,totalUsers,activeUsers,usersWithSignInData,role,users,signedIn\n" + + "31,2026-09-08T12:00:00Z,0,0,0,,0,0\n" + if buf.String() != expected { + t.Errorf("expected %q, got %q", expected, buf.String()) + } +} + +// TestRenderUserReportWithoutSignInData covers deployments that never record a +// sign-in, e.g. because the identity backend is read only. The users are still +// grouped by role there, but the sign-in counts are not available and must not +// be rendered as 0. +func TestRenderUserReportWithoutSignInData(t *testing.T) { + report := userReport{ + GeneratedAt: time.Date(2026, 10, 9, 12, 0, 0, 0, time.UTC), + Days: 31, + ActiveSince: time.Date(2026, 9, 8, 12, 0, 0, 0, time.UTC), + TotalUsers: 6, + ActiveUsers: nil, + UsersWithSignInData: 0, + SignInReported: true, + Roles: []roleCount{ + {Role: "User", Users: 5, SignedIn: nil}, + {Role: "Admin", Users: 1, SignedIn: nil}, + }, + } + + testCases := []struct { + format string + expected []string + notExpected []string + }{ + { + format: _reportOutputTable, + expected: []string{ + "Signed in within the last 31 days: N/A", + "Warning: not a single user has a recorded sign-in", + // the grouping has to be there regardless of the missing data + "Users in total: 6", "User", "Admin", "N/A", + }, + }, + { + format: _reportOutputJSON, + expected: []string{`"activeUsers": null`, `"signedIn": null`, `"usersWithSignInData": 0`}, + notExpected: []string{`"activeUsers": 0`, `"signedIn": 0`}, + }, + { + format: _reportOutputYAML, + expected: []string{"activeUsers: null", "signedIn: null"}, + notExpected: []string{"activeUsers: 0", "signedIn: 0"}, + }, + { + format: _reportOutputCSV, + expected: []string{ + "days,activeSince,totalUsers,activeUsers,usersWithSignInData,role,users,signedIn\n" + + "31,2026-09-08T12:00:00Z,6,,0,User,5,\n" + + "31,2026-09-08T12:00:00Z,6,,0,Admin,1,\n", + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.format, func(t *testing.T) { + var buf bytes.Buffer + if err := renderUserReport(&buf, report, tc.format); err != nil { + t.Fatalf("unexpected error: %v", err) + } + actual := regexp.MustCompile(` +`).ReplaceAllString(buf.String(), " ") + for _, expected := range tc.expected { + if !strings.Contains(actual, expected) { + t.Errorf("expected output to contain %q, got:\n%s", expected, buf.String()) + } + } + for _, notExpected := range tc.notExpected { + if strings.Contains(actual, notExpected) { + t.Errorf("expected output not to contain %q, got:\n%s", notExpected, buf.String()) + } + } + }) + } +} + +// TestCountUsersByRoleWithoutWindow covers the default: without a window +// the sign-in data is not looked at at all, even on an instance that records +// it, and the users are still grouped by their role. +func TestCountUsersByRoleWithoutWindow(t *testing.T) { + recent := time.Now().UTC().Add(-time.Hour) + users := []libregraph.User{ + testUser("alan", &recent, userRoleID), + testUser("lynn", nil, userRoleID), + testUser("dennis", &recent, adminRoleID), + testUser("mary", nil), + } + + roles, active, withSignInfo := countUsersByRole(users, testRoleNames(), nil) + + if active != nil { + t.Errorf("expected no count of active users, got %d", *active) + } + if withSignInfo != 0 { + t.Errorf("expected no sign-in data to be counted, got %d", withSignInfo) + } + + expectedRoles := []roleCount{ + {Role: "User", Users: 2}, + {Role: _reportNoRole, Users: 1}, + {Role: "Admin", Users: 1}, + } + if len(roles) != len(expectedRoles) { + t.Fatalf("expected %d roles, got %d", len(expectedRoles), len(roles)) + } + for i, expected := range expectedRoles { + got := roles[i] + if got.Role != expected.Role || got.Users != expected.Users { + t.Errorf("role %d: expected %s/%d, got %s/%d", + i, expected.Role, expected.Users, got.Role, got.Users) + } + if got.SignedIn != nil { + t.Errorf("role %s: expected no sign-in count, got %d", got.Role, *got.SignedIn) + } + } +} + +// TestRenderUserReportWithoutSignIn makes sure the default leaves every +// trace of the sign-in window out of the output, rather than reporting it as +// null or N/A. +func TestRenderUserReportWithoutSignIn(t *testing.T) { + report := userReport{ + GeneratedAt: time.Date(2026, 10, 9, 12, 0, 0, 0, time.UTC), + TotalUsers: 6, + Roles: []roleCount{ + {Role: "User", Users: 4}, + {Role: "Admin", Users: 2}, + }, + } + + testCases := []struct { + format string + expected []string + notExpected []string + }{ + { + format: _reportOutputTable, + expected: []string{"Users in total: 6", "Role", "Users", "User", "Admin"}, + notExpected: []string{"Sign-in window", "Signed in within", "recorded sign-in", "N/A", "Warning"}, + }, + { + format: _reportOutputJSON, + expected: []string{`"totalUsers": 6`, `"role": "User"`, `"users": 4`}, + notExpected: []string{"signedIn", "activeUsers", "activeSince", "usersWithSignInData", `"days"`, "null"}, + }, + { + format: _reportOutputCSV, + expected: []string{"totalUsers,role,users\n6,User,4\n6,Admin,2\n"}, + notExpected: []string{"signedIn", "activeUsers", "activeSince", "usersWithSignInData"}, + }, + { + format: _reportOutputYAML, + expected: []string{"totalUsers: 6", "- role: User", "users: 4"}, + notExpected: []string{"signedIn", "activeUsers", "activeSince", "usersWithSignInData", "days:"}, + }, + } + + for _, tc := range testCases { + t.Run(tc.format, func(t *testing.T) { + var buf bytes.Buffer + if err := renderUserReport(&buf, report, tc.format); err != nil { + t.Fatalf("unexpected error: %v", err) + } + // collapse the padding the table format uses to align its labels + actual := regexp.MustCompile(` +`).ReplaceAllString(buf.String(), " ") + for _, expected := range tc.expected { + if !strings.Contains(actual, expected) { + t.Errorf("expected output to contain %q, got:\n%s", expected, buf.String()) + } + } + for _, notExpected := range tc.notExpected { + if strings.Contains(actual, notExpected) { + t.Errorf("expected output not to contain %q, got:\n%s", notExpected, buf.String()) + } + } + }) + } +} + +// TestRenderUserReportWithoutSignInWithoutUsers keeps the csv total readable +// when there is not a single user to group. +func TestRenderUserReportWithoutSignInWithoutUsers(t *testing.T) { + report := userReport{ + GeneratedAt: time.Date(2026, 10, 9, 12, 0, 0, 0, time.UTC), + Roles: []roleCount{}, + } + + var buf bytes.Buffer + if err := renderUserReport(&buf, report, _reportOutputCSV); err != nil { + t.Fatalf("unexpected error: %v", err) + } + expected := "totalUsers,role,users\n0,,0\n" + if buf.String() != expected { + t.Errorf("expected %q, got %q", expected, buf.String()) + } +} + +// TestNodeProtocol covers the TLS resolution of a registry node. The registry +// reports "http" for every HTTP service, so only the use_tls metadata tells a +// TLS listener apart from a plain one. +func TestNodeProtocol(t *testing.T) { + testCases := []struct { + name string + metadata map[string]string + expected string + }{ + { + name: "plain http service", + metadata: map[string]string{"protocol": "http"}, + expected: "http", + }, + { + name: "http service with TLS enabled", + metadata: map[string]string{"protocol": "http", "use_tls": "true"}, + expected: "https", + }, + { + name: "use_tls wins over the reported protocol", + metadata: map[string]string{"protocol": "grpc", "use_tls": "true"}, + expected: "https", + }, + { + name: "use_tls false is plain", + metadata: map[string]string{"protocol": "http", "use_tls": "false"}, + expected: "http", + }, + { + name: "missing protocol falls back to http", + metadata: map[string]string{}, + expected: "http", + }, + { + name: "missing protocol with TLS enabled", + metadata: map[string]string{"use_tls": "true"}, + expected: "https", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + if got := nodeProtocol(tc.metadata); got != tc.expected { + t.Errorf("expected %q, got %q", tc.expected, got) + } + }) + } +} + +// TestReportCommandFlags pins the command line surface: the shorthands must +// stay stable for scripts, and a new flag must not silently take one that is +// already in use. +func TestReportCommandFlags(t *testing.T) { + cmd := ReportCommand(&config.Config{}) + + testCases := []struct { + name string + shorthand string + defValue string + }{ + {name: _reportDaysFlagName, shorthand: "d", defValue: "31"}, + {name: _reportOutputFlagName, shorthand: "o", defValue: _reportOutputTable}, + {name: _reportTimeoutFlagName, shorthand: "t", defValue: "5m0s"}, + {name: _reportSignInFlagName, shorthand: "", defValue: "false"}, + {name: _reportInsecureFlagName, shorthand: "", defValue: "false"}, + } + + seen := map[string]string{} + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + flag := cmd.Flags().Lookup(tc.name) + if flag == nil { + t.Fatalf("flag --%s is not registered", tc.name) + } + if flag.Shorthand != tc.shorthand { + t.Errorf("expected shorthand %q for --%s, got %q", tc.shorthand, tc.name, flag.Shorthand) + } + if flag.DefValue != tc.defValue { + t.Errorf("expected default %q for --%s, got %q", tc.defValue, tc.name, flag.DefValue) + } + }) + if tc.shorthand != "" { + if other, taken := seen[tc.shorthand]; taken { + t.Errorf("shorthand -%s is used by both --%s and --%s", tc.shorthand, other, tc.name) + } + seen[tc.shorthand] = tc.name + } + } +} + +// TestSignInUnavailable covers when --with-sign-in may be used at all. +// OpenCloud stores the last sign-in on the user entry in LDAP, so a read-only +// or non-LDAP backend records nothing and the flag has to be refused rather +// than producing a column of N/A. +func TestSignInUnavailable(t *testing.T) { + testCases := []struct { + name string + backend string + writeEnabled bool + available bool + contains string + }{ + { + name: "writable ldap backend", + backend: "ldap", + writeEnabled: true, + available: true, + }, + { + name: "read-only ldap backend", + backend: "ldap", + writeEnabled: false, + available: false, + contains: "OC_LDAP_SERVER_WRITE_ENABLED", + }, + { + name: "cs3 backend never records sign-ins", + backend: "cs3", + writeEnabled: true, + available: false, + contains: "cs3", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + cfg := &config.Config{Graph: &graphconfig.Config{}} + cfg.Graph.Identity.Backend = tc.backend + cfg.Graph.Identity.LDAP.WriteEnabled = tc.writeEnabled + + reason := signInUnavailable(cfg) + if tc.available { + if reason != "" { + t.Errorf("expected sign-ins to be available, got refusal %q", reason) + } + return + } + if reason == "" { + t.Fatal("expected a refusal, got none") + } + if !strings.Contains(reason, tc.contains) { + t.Errorf("expected the refusal to mention %q, got %q", tc.contains, reason) + } + }) + } +} + +// TestNewGraphHTTPClient pins the TLS floor and makes sure the certificate +// check is only skipped on request. It also guards the transport clone: the +// defaults for proxy support and HTTP/2 must survive, which a bare +// &http.Transport{} would silently drop. +func TestNewGraphHTTPClient(t *testing.T) { + testCases := []struct { + name string + insecure bool + }{ + {name: "verifies certificates by default", insecure: false}, + {name: "skips verification when asked", insecure: true}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + client := newGraphHTTPClient(reportOptions{timeout: 42 * time.Second, insecure: tc.insecure}) + + if client.Timeout != 42*time.Second { + t.Errorf("expected the timeout to be carried over, got %s", client.Timeout) + } + + transport, ok := client.Transport.(*http.Transport) + if !ok { + t.Fatalf("expected an *http.Transport, got %T", client.Transport) + } + if transport.TLSClientConfig.MinVersion != tls.VersionTLS12 { + t.Errorf("expected TLS 1.2 as the minimum, got %#x", transport.TLSClientConfig.MinVersion) + } + if transport.TLSClientConfig.InsecureSkipVerify != tc.insecure { + t.Errorf("expected InsecureSkipVerify to be %v, got %v", + tc.insecure, transport.TLSClientConfig.InsecureSkipVerify) + } + + // cloned from the default transport, not built from scratch + if transport.Proxy == nil { + t.Error("expected the default proxy support to survive the clone") + } + if !transport.ForceAttemptHTTP2 { + t.Error("expected HTTP/2 to stay enabled after the clone") + } + }) + } +} + +// TestConfiguredGraphURL covers the fallback used when the service registry +// holds no entry, e.g. a deployment running with MICRO_REGISTRY=memory. +func TestConfiguredGraphURL(t *testing.T) { + newCfg := func(addr, root string, tlsEnabled bool) *config.Config { + cfg := &config.Config{ + Commons: &shared.Commons{ + HTTPServiceTLS: shared.HTTPServiceTLS{Enabled: tlsEnabled}, + }, + Graph: &graphconfig.Config{}, + } + cfg.Graph.HTTP.Addr = addr + cfg.Graph.HTTP.Root = root + return cfg + } + + testCases := []struct { + name string + cfg *config.Config + expected string + }{ + { + name: "plain http", + cfg: newCfg("127.0.0.1:9120", "/graph", false), + expected: "http://127.0.0.1:9120/graph", + }, + { + name: "https when the http services serve TLS", + cfg: newCfg("127.0.0.1:9120", "/graph", true), + expected: "https://127.0.0.1:9120/graph", + }, + { + name: "no address configured leaves it to the caller", + cfg: newCfg("", "/graph", false), + expected: "", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + if got := configuredGraphURL(tc.cfg); got != tc.expected { + t.Errorf("expected %q, got %q", tc.expected, got) + } + }) + } +} + +// TestConfiguredGatewayAddress covers the dns:/// fallback target. A wildcard +// bind address has to become loopback: the report runs next to the gateway, and +// 0.0.0.0 is not a dialable destination. +func TestConfiguredGatewayAddress(t *testing.T) { + newCfg := func(addr string) *config.Config { + cfg := &config.Config{Gateway: &gatewayconfig.Config{}} + cfg.Gateway.GRPC.Addr = addr + return cfg + } + + testCases := []struct { + name string + cfg *config.Config + expected string + }{ + {name: "loopback stays", cfg: newCfg("127.0.0.1:9142"), expected: "dns:///127.0.0.1:9142"}, + {name: "ipv4 wildcard becomes loopback", cfg: newCfg("0.0.0.0:9142"), expected: "dns:///127.0.0.1:9142"}, + {name: "ipv6 wildcard becomes loopback", cfg: newCfg("[::]:9142"), expected: "dns:///127.0.0.1:9142"}, + {name: "empty host becomes loopback", cfg: newCfg(":9142"), expected: "dns:///127.0.0.1:9142"}, + {name: "a real host is kept", cfg: newCfg("gateway.internal:9142"), expected: "dns:///gateway.internal:9142"}, + {name: "no address configured", cfg: newCfg(""), expected: ""}, + {name: "not a host:port", cfg: newCfg("eu.opencloud.api.gateway"), expected: ""}, + {name: "no gateway config at all", cfg: &config.Config{}, expected: ""}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + if got := configuredGatewayAddress(tc.cfg); got != tc.expected { + t.Errorf("expected %q, got %q", tc.expected, got) + } + }) + } +}