mirror of
https://github.com/opencloud-eu/opencloud.git
synced 2026-11-27 10:34:42 -05:00
fix: audit log follow-ups from the review
Assisted-by: Claude Code:claude-opus-5-5
This commit is contained in:
18 files changed
+260
-38
No files matched your search
@@ -38,9 +38,3 @@ func New(ctx context.Context, service string, s Settings, nats raw.Config, logge
|
||||
}
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// Close flushes the records the emitter still holds. It does nothing for an
|
||||
// emitter that holds none.
|
||||
func Close(e audit.Emitter) {
|
||||
audit.CloseEmitter(e)
|
||||
}
|
||||
@@ -18,7 +18,7 @@ func TestNew(t *testing.T) {
|
||||
e, err := New(context.Background(), "graph", Settings{}, raw.Config{}, logger)
|
||||
require.NoError(t, err)
|
||||
assert.IsType(t, audit.Discard{}, e)
|
||||
assert.NotPanics(t, func() { Close(e) })
|
||||
assert.NotPanics(t, func() { audit.CloseEmitter(e) })
|
||||
})
|
||||
|
||||
t.Run("without endpoint", func(t *testing.T) {
|
||||
|
||||
@@ -10,7 +10,7 @@ The design is described in [ADR 0006](../../docs/adr/0006-audit-logging.md).
|
||||
|
||||
Two things are needed:
|
||||
|
||||
- The services must emit audit events. Set `OC_AUDIT_ENABLED=true`. It is read by the proxy, graph, frontend, sharing and storage-users services, each of them also has its own variable, e.g. `PROXY_AUDIT_ENABLED`.
|
||||
- Set `OC_AUDIT_ENABLED=true`. It makes the proxy, graph, frontend, sharing and storage-users services emit audit events, and switches the audit service from the [legacy audit log](#legacy-audit-log) to the audit stream. Each service also has its own variable, e.g. `PROXY_AUDIT_ENABLED`, and `AUDIT_STREAM_ENABLED` for the audit service. If you use those instead, set `AUDIT_STREAM_ENABLED=true` as well, otherwise the audit service keeps running the legacy audit log.
|
||||
- The audit service must run. It is not started automatically when running as single binary via `opencloud server` or as docker container. Add it with `OC_ADD_RUN_SERVICES=audit`.
|
||||
|
||||
Events emitted while the audit service is not running are kept in the stream and written when it starts, see `AUDIT_STREAM_MAX_AGE`.
|
||||
@@ -89,14 +89,14 @@ An update only lists what it changed, e.g. only `role`. `display_name`, `descrip
|
||||
|
||||
`space.update` lists what changed in `change.after`: `name`, `description`, `alias`, and `image` and `readme` with the ID of the file. An empty value means the attribute was removed.
|
||||
|
||||
The catalog is defined in reva's `pkg/audit`. Some of its events are not emitted yet: app and guest tokens, previews, open in app, copies, deleted versions, the malware finding, OCM, settings, configuration and CLI commands, app role and sharing role definitions, and `access.denied`. `group.update` is only recorded when it fails.
|
||||
The catalog is defined in reva's `pkg/audit`. Some of its events are not emitted yet: app and guest tokens, previews, open in app, copies, deleted versions, the malware finding, OCM, settings, configuration and CLI commands, app role and sharing role definitions, and `access.denied`.
|
||||
|
||||
Some actions are left out on purpose:
|
||||
|
||||
- Thumbnails are not audited. `file.preview` is opening a file in the preview app.
|
||||
- Uploads and downloads are recorded when the transfer is done. Uploads and downloads by OpenCloud itself, e.g. for a copy, thumbnails, search or an archive, are not recorded.
|
||||
- A download that is resumed or seeked makes many range requests, only the one starting at the first byte counts.
|
||||
- `auth.login` is recorded for a new OIDC session. When the access token has a session ID (`sid`), as with Keycloak, only the first token of a session and OIDC client is a login; renewed tokens are not. Without a session ID, e.g. with the built-in identity provider, every new access token is recorded as a login, also the ones a client gets by renewing its token. Basic auth and app tokens authenticate every single request, for them only failed logins are recorded. Expired OIDC tokens are part of the normal token renewal and are not recorded as failed logins.
|
||||
- `auth.login` is recorded for a new OIDC session. When the access token has a session ID (`sid`), as with Keycloak, only the first token of a session and OIDC client is a login; renewed tokens are not. The proxy keeps the sessions it recorded for a day, in the database `audit-logins` of the store of the userinfo cache (`PROXY_OIDC_USERINFO_CACHE_STORE`). With the `memory` store every proxy replica records the login once, use `nats-js-kv` with more than one proxy. Without a session ID, e.g. with the built-in identity provider, every new access token is recorded as a login, also the ones a client gets by renewing its token. Basic auth and app tokens authenticate every single request, for them only failed logins are recorded. Expired OIDC tokens are part of the normal token renewal and are not recorded as failed logins.
|
||||
- `public_link.access` is recorded once per link and client within 30 minutes, every failed attempt is recorded. The web client asking whether a link needs a password is not an attempt.
|
||||
- Shares accepted automatically, see `SHARING_AUTO_ACCEPT_SHARES`, are not recorded as `share.accept`. The `share.create` of the sharer is the record.
|
||||
|
||||
@@ -104,7 +104,7 @@ Some actions are left out on purpose:
|
||||
|
||||
The audit service writes to stdout, one record per line and nothing else, see `AUDIT_OUTPUT_STDOUT`. Any log agent can pick it up. When the audit service runs with other services in one process or container, their logs share the same stdout; run it in its own container to keep the audit log separate.
|
||||
|
||||
With `AUDIT_OUTPUT_OTLP_ENDPOINT` the audit service also sends the records to an OpenTelemetry Collector as OTLP logs over gRPC. The endpoint is `host:port` without a scheme, the audit service does not start with an invalid value. Use `AUDIT_OUTPUT_OTLP_INSECURE` for a Collector without TLS. Every record is an OpenTelemetry event: the event name is `event.name`, the fields are attributes and the body is the record as JSON. The resource names the service that emitted the event, `service.name` and `service.version` are therefore no attributes; the instrumentation scope is the audit service. The Collector routes the records to the SIEM, e.g. with its Splunk HEC, Elasticsearch, OpenSearch or syslog exporters. Every record is sent on its own and acknowledged only after the Collector accepted it, so a Collector outage delays the records but loses none.
|
||||
With `AUDIT_OUTPUT_OTLP_ENDPOINT` the audit service also sends the records to an OpenTelemetry Collector as OTLP logs over gRPC. The endpoint is `host:port` without a scheme, the audit service does not start with an invalid value. Use `AUDIT_OUTPUT_OTLP_INSECURE` for a Collector without TLS. Every record is an OpenTelemetry event: the event name is `event.name`, the fields are attributes and the body is the record as JSON. Both on purpose: Collector processors filter and route on the attributes, exporters like syslog or Splunk HEC send the body. A record is about 1 KB, sending it twice costs little. The resource names the service that emitted the event, `service.name` and `service.version` are therefore no attributes; the instrumentation scope is the audit service. The Collector routes the records to the SIEM, e.g. with its Splunk HEC, Elasticsearch, OpenSearch or syslog exporters. Every record is sent on its own and acknowledged only after the Collector accepted it, so a Collector outage delays the records but loses none.
|
||||
|
||||
At least one output must be enabled.
|
||||
|
||||
@@ -146,8 +146,10 @@ Alert on dropped events and on a growing consumer lag.
|
||||
|
||||
## Legacy Audit Log
|
||||
|
||||
The audit log of earlier versions is still available with `AUDIT_LEGACY_ENABLED=true` and will be removed in a later version. It reads the domain events instead of the audit stream and uses the `AUDIT_LOG_TO_CONSOLE`, `AUDIT_LOG_TO_FILE`, `AUDIT_FILEPATH` and `AUDIT_FORMAT` settings. Its records have a different format:
|
||||
As long as `OC_AUDIT_ENABLED` is not `true`, the audit service runs the audit log of earlier versions, so an existing audit log keeps working after an upgrade. It is deprecated and will be removed in a later version. It reads the domain events instead of the audit stream and uses the `AUDIT_LOG_TO_CONSOLE`, `AUDIT_LOG_TO_FILE`, `AUDIT_FILEPATH` and `AUDIT_FORMAT` settings. Its records have a different format:
|
||||
|
||||
```json
|
||||
{"RemoteAddr":"","User":"user_id","URL":"","Method":"","UserAgent":"","Time":"","App":"admin_audit","Message":"user 'user_id' trashed file 'item_id'","Action":"file_delete","CLI":false,"Level":1,"Path":"path","Owner":"user_id","FileID":"item_id"}
|
||||
```
|
||||
|
||||
To move to the audit stream, set `OC_AUDIT_ENABLED=true` for all services. The records then have the format described above, and there is no output to a file: point a log agent at stdout or set `AUDIT_OUTPUT_OTLP_ENDPOINT` before you switch.
|
||||
@@ -50,8 +50,8 @@ func Server(cfg *config.Config) *cobra.Command {
|
||||
defer svcCancel()
|
||||
|
||||
connName := generators.GenerateConnectionName(cfg.Service.Name, generators.NTypeBus)
|
||||
if cfg.Legacy.Enabled {
|
||||
logger.Warn().Msg("the legacy audit log is deprecated, use the audit stream")
|
||||
if !cfg.Stream.Enabled {
|
||||
logger.Warn().Msg("the legacy audit log is deprecated and will be removed, set OC_AUDIT_ENABLED=true to switch to the audit stream")
|
||||
if err := addLegacy(svcCtx, svcCancel, gr, cfg, connName, logger); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -18,8 +18,7 @@ type Config struct {
|
||||
Stream Stream `yaml:"stream"`
|
||||
Output Output `yaml:"output"`
|
||||
|
||||
// Legacy runs the old audit log on the domain events instead of the audit stream.
|
||||
Legacy Legacy `yaml:"legacy"`
|
||||
// Auditlog configures the legacy audit log, which runs while Stream.Enabled is false.
|
||||
Auditlog Auditlog `yaml:"auditlog"`
|
||||
|
||||
Context context.Context `yaml:"-"`
|
||||
@@ -38,6 +37,10 @@ type Events struct {
|
||||
|
||||
// Stream configures the JetStream stream "audit", the buffer between the services and the audit service.
|
||||
type Stream struct {
|
||||
// Enabled is read from OC_AUDIT_ENABLED like in the services that emit the audit events, so that
|
||||
// one variable switches the whole installation, and existing installations keep the legacy audit
|
||||
// log until they turn the new one on.
|
||||
Enabled bool `yaml:"enabled" env:"OC_AUDIT_ENABLED;AUDIT_STREAM_ENABLED" desc:"Write the audit records of the audit stream. OC_AUDIT_ENABLED also makes the services emit them. If false, the deprecated legacy audit log runs instead, with the AUDIT_LOG_TO_CONSOLE, AUDIT_LOG_TO_FILE, AUDIT_FILEPATH and AUDIT_FORMAT settings." introductionVersion:"%%NEXT%%"`
|
||||
Replicas int `yaml:"replicas" env:"AUDIT_STREAM_REPLICAS" desc:"Number of replicas of the audit stream in a clustered NATS. Use 3 in production clusters." introductionVersion:"%%NEXT%%"`
|
||||
MaxAge time.Duration `yaml:"max_age" env:"AUDIT_STREAM_MAX_AGE" desc:"How long audit events stay in the stream. The stream is a buffer for outages of the audit service, not the archive. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"`
|
||||
}
|
||||
@@ -54,15 +57,10 @@ type OTLP struct {
|
||||
Insecure bool `yaml:"insecure" env:"AUDIT_OUTPUT_OTLP_INSECURE" desc:"Connect to the OpenTelemetry Collector without TLS." introductionVersion:"%%NEXT%%"`
|
||||
}
|
||||
|
||||
// Legacy configures the legacy audit log.
|
||||
type Legacy struct {
|
||||
Enabled bool `yaml:"enabled" env:"AUDIT_LEGACY_ENABLED" desc:"Run the legacy audit log on the domain events instead of the audit stream. It uses the AUDIT_LOG_TO_CONSOLE, AUDIT_LOG_TO_FILE, AUDIT_FILEPATH and AUDIT_FORMAT settings." introductionVersion:"%%NEXT%%" deprecationVersion:"%%NEXT%%" removalVersion:"%%NEXT_PRODUCTION_VERSION%%" deprecationInfo:"The legacy audit log is replaced by the audit stream and will be removed." deprecationReplacement:"AUDIT_OUTPUT_STDOUT"`
|
||||
}
|
||||
|
||||
// Auditlog holds audit log information, only used by the legacy audit log.
|
||||
type Auditlog struct {
|
||||
LogToConsole bool `yaml:"log_to_console" env:"AUDIT_LOG_TO_CONSOLE" desc:"Logs to stdout if set to 'true'. Independent of the LOG_TO_FILE option." introductionVersion:"1.0.0"`
|
||||
LogToFile bool `yaml:"log_to_file" env:"AUDIT_LOG_TO_FILE" desc:"Logs to file if set to 'true'. Independent of the LOG_TO_CONSOLE option." introductionVersion:"1.0.0"`
|
||||
FilePath string `yaml:"filepath" env:"AUDIT_FILEPATH" desc:"Filepath of the logfile. Mandatory if LOG_TO_FILE is set to 'true'." introductionVersion:"1.0.0"`
|
||||
Format string `yaml:"format" env:"AUDIT_FORMAT" desc:"Log format. Supported values are '' (empty) and 'json'. Using 'json' is advised, '' (empty) renders the 'minimal' format. See the text description for more details." introductionVersion:"1.0.0"`
|
||||
LogToConsole bool `yaml:"log_to_console" env:"AUDIT_LOG_TO_CONSOLE" desc:"Logs to stdout if set to 'true'. Independent of the LOG_TO_FILE option. Only used by the legacy audit log." introductionVersion:"1.0.0" deprecationVersion:"%%NEXT%%" removalVersion:"%%NEXT_PRODUCTION_VERSION%%" deprecationInfo:"The legacy audit log is replaced by the audit stream, enable it with OC_AUDIT_ENABLED." deprecationReplacement:"AUDIT_OUTPUT_STDOUT"`
|
||||
LogToFile bool `yaml:"log_to_file" env:"AUDIT_LOG_TO_FILE" desc:"Logs to file if set to 'true'. Independent of the LOG_TO_CONSOLE option. Only used by the legacy audit log." introductionVersion:"1.0.0" deprecationVersion:"%%NEXT%%" removalVersion:"%%NEXT_PRODUCTION_VERSION%%" deprecationInfo:"The legacy audit log is replaced by the audit stream, enable it with OC_AUDIT_ENABLED. The audit stream writes to stdout or to an OpenTelemetry Collector, not to a file." deprecationReplacement:"AUDIT_OUTPUT_OTLP_ENDPOINT"`
|
||||
FilePath string `yaml:"filepath" env:"AUDIT_FILEPATH" desc:"Filepath of the logfile. Mandatory if LOG_TO_FILE is set to 'true'. Only used by the legacy audit log." introductionVersion:"1.0.0" deprecationVersion:"%%NEXT%%" removalVersion:"%%NEXT_PRODUCTION_VERSION%%" deprecationInfo:"The legacy audit log is replaced by the audit stream, enable it with OC_AUDIT_ENABLED. The audit stream writes to stdout or to an OpenTelemetry Collector, not to a file." deprecationReplacement:"AUDIT_OUTPUT_OTLP_ENDPOINT"`
|
||||
Format string `yaml:"format" env:"AUDIT_FORMAT" desc:"Log format. Supported values are '' (empty) and 'json'. Using 'json' is advised, '' (empty) renders the 'minimal' format. See the text description for more details. Only used by the legacy audit log." introductionVersion:"1.0.0" deprecationVersion:"%%NEXT%%" removalVersion:"%%NEXT_PRODUCTION_VERSION%%" deprecationInfo:"The legacy audit log is replaced by the audit stream, enable it with OC_AUDIT_ENABLED. The audit stream always writes JSON." deprecationReplacement:""`
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// Copyright 2026 OpenCloud GmbH <mail@opencloud.eu>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package parser_test
|
||||
|
||||
import (
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
|
||||
"github.com/opencloud-eu/opencloud/services/audit/pkg/config/defaults"
|
||||
"github.com/opencloud-eu/opencloud/services/audit/pkg/config/parser"
|
||||
)
|
||||
|
||||
var _ = Describe("ParseConfig", func() {
|
||||
BeforeEach(func() {
|
||||
GinkgoT().Setenv("OC_CONFIG_DIR", GinkgoT().TempDir())
|
||||
})
|
||||
|
||||
// an installation that only adds the audit service keeps its legacy audit log after an upgrade,
|
||||
// the variable that makes the services emit audit events also switches to the audit stream
|
||||
DescribeTable("switches between the legacy audit log and the audit stream",
|
||||
func(env map[string]string, stream bool) {
|
||||
for k, v := range env {
|
||||
GinkgoT().Setenv(k, v)
|
||||
}
|
||||
|
||||
cfg := defaults.DefaultConfig()
|
||||
Expect(parser.ParseConfig(cfg)).To(Succeed())
|
||||
Expect(cfg.Stream.Enabled).To(Equal(stream))
|
||||
},
|
||||
Entry("legacy audit log by default", map[string]string{}, false),
|
||||
Entry("audit stream with OC_AUDIT_ENABLED", map[string]string{
|
||||
"OC_AUDIT_ENABLED": "true",
|
||||
}, true),
|
||||
Entry("audit stream with AUDIT_STREAM_ENABLED", map[string]string{
|
||||
"AUDIT_STREAM_ENABLED": "true",
|
||||
}, true),
|
||||
Entry("AUDIT_STREAM_ENABLED wins when both are set", map[string]string{
|
||||
"OC_AUDIT_ENABLED": "true",
|
||||
"AUDIT_STREAM_ENABLED": "false",
|
||||
}, false),
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
// Copyright 2026 OpenCloud GmbH <mail@opencloud.eu>
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package parser_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/onsi/ginkgo/v2"
|
||||
. "github.com/onsi/gomega"
|
||||
)
|
||||
|
||||
func TestParser(t *testing.T) {
|
||||
RegisterFailHandler(Fail)
|
||||
RunSpecs(t, "Parser Suite")
|
||||
}
|
||||
@@ -179,19 +179,37 @@ func (w *Writer) Run(ctx context.Context, js jetstream.JetStream, cfg audit.Stre
|
||||
iter.Stop()
|
||||
}()
|
||||
|
||||
var delay time.Duration
|
||||
for {
|
||||
msg, err := iter.Next()
|
||||
if err != nil {
|
||||
if errors.Is(err, jetstream.ErrMsgIteratorClosed) || ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
w.log.Error().Err(err).Msg("reading the audit stream failed")
|
||||
// without a pause a persistent error fills the log as fast as it repeats
|
||||
delay = nextReadDelay(delay, w.RetryDelay)
|
||||
w.log.Error().Err(err).Dur("retry_in", delay).Msg("reading the audit stream failed")
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-time.After(delay):
|
||||
}
|
||||
continue
|
||||
}
|
||||
delay = 0
|
||||
w.Handle(ctx, msg)
|
||||
}
|
||||
}
|
||||
|
||||
// nextReadDelay is the pause after a failed read of the stream: 100ms after the
|
||||
// first failure, then doubled up to limit.
|
||||
func nextReadDelay(d, limit time.Duration) time.Duration {
|
||||
if d == 0 {
|
||||
return min(100*time.Millisecond, limit)
|
||||
}
|
||||
return min(2*d, limit)
|
||||
}
|
||||
|
||||
func (w *Writer) reportLag(ctx context.Context, cons jetstream.Consumer) {
|
||||
t := time.NewTicker(15 * time.Second)
|
||||
defer t.Stop()
|
||||
|
||||
@@ -175,6 +175,19 @@ func TestLagCountsUnackedRecords(t *testing.T) {
|
||||
assert.Equal(t, float64(7), lag(&jetstream.ConsumerInfo{NumPending: 3, NumAckPending: 4}))
|
||||
}
|
||||
|
||||
func TestNextReadDelay(t *testing.T) {
|
||||
var d time.Duration
|
||||
var got []time.Duration
|
||||
for range 8 {
|
||||
d = nextReadDelay(d, 5*time.Second)
|
||||
got = append(got, d)
|
||||
}
|
||||
assert.Equal(t, []time.Duration{
|
||||
100 * time.Millisecond, 200 * time.Millisecond, 400 * time.Millisecond, 800 * time.Millisecond,
|
||||
1600 * time.Millisecond, 3200 * time.Millisecond, 5 * time.Second, 5 * time.Second,
|
||||
}, got)
|
||||
}
|
||||
|
||||
func TestRunEndToEnd(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/opencloud-eu/opencloud/services/graph/pkg/server/http"
|
||||
evc "github.com/opencloud-eu/opencloud/services/graph/pkg/service/events"
|
||||
svc "github.com/opencloud-eu/opencloud/services/graph/pkg/service/v0"
|
||||
"github.com/opencloud-eu/reva/v3/pkg/audit"
|
||||
"github.com/opencloud-eu/reva/v3/pkg/events"
|
||||
"github.com/opencloud-eu/reva/v3/pkg/events/raw"
|
||||
"github.com/opencloud-eu/reva/v3/pkg/events/stream"
|
||||
@@ -138,7 +139,7 @@ func Server(cfg *config.Config) *cobra.Command {
|
||||
logger.Error().Err(err).Msg("Error initializing the audit emitter")
|
||||
return err
|
||||
}
|
||||
defer auditemitter.Close(auditEmitter)
|
||||
defer audit.CloseEmitter(auditEmitter)
|
||||
|
||||
gr := runner.NewGroup()
|
||||
|
||||
|
||||
@@ -127,7 +127,12 @@ func (g Graph) auditRoute(d *audit.Definition, idParam string, report func(audit
|
||||
target := audit.Target{ID: "unknown"}
|
||||
switch {
|
||||
case idParam != "":
|
||||
// the IDs of the domain events are unescaped, a failure and a
|
||||
// success record of the same object must have the same ID
|
||||
target.ID = chi.URLParam(r, idParam)
|
||||
if unescaped, err := url.PathUnescape(target.ID); err == nil {
|
||||
target.ID = unescaped
|
||||
}
|
||||
case d == audit.UserPasswordChange:
|
||||
if u, ok := revactx.ContextGetUser(r.Context()); ok {
|
||||
target.ID = u.GetId().GetOpaqueId()
|
||||
|
||||
@@ -4,14 +4,19 @@ import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
"github.com/go-chi/chi/v5"
|
||||
libregraph "github.com/opencloud-eu/libre-graph-api-go"
|
||||
"github.com/opencloud-eu/opencloud/pkg/log"
|
||||
identitymocks "github.com/opencloud-eu/opencloud/services/graph/pkg/identity/mocks"
|
||||
"github.com/opencloud-eu/reva/v3/pkg/audit"
|
||||
revactx "github.com/opencloud-eu/reva/v3/pkg/ctx"
|
||||
"github.com/opencloud-eu/reva/v3/pkg/events"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
@@ -169,3 +174,43 @@ func TestPersonalDataExportForAnotherUserIsDenied(t *testing.T) {
|
||||
require.Len(t, rec.events, 2)
|
||||
assert.Equal(t, audit.OutcomeFailure, rec.events[1].Outcome, "a bad request for oneself stays a failure")
|
||||
}
|
||||
|
||||
func TestAuditRoutesUnescapeTheTargetID(t *testing.T) {
|
||||
rec := &recordingEmitter{}
|
||||
g := Graph{auditEmitter: rec}
|
||||
router := chi.NewRouter()
|
||||
router.With(g.auditOnError(audit.GroupDelete, "groupID")).Delete("/groups/{groupID}", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
})
|
||||
|
||||
router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodDelete, "/groups/a%2Fb", nil))
|
||||
|
||||
require.Len(t, rec.events, 1)
|
||||
assert.Equal(t, "a/b", rec.events[0].Target.ID, "the same ID as in the records of the domain events")
|
||||
}
|
||||
|
||||
func TestGroupRenameIsAudited(t *testing.T) {
|
||||
rec := &recordingEmitter{}
|
||||
backend := &identitymocks.Backend{}
|
||||
backend.On("GetGroup", mock.Anything, "g-1", mock.Anything).Return(&libregraph.Group{DisplayName: libregraph.PtrString("old")}, nil)
|
||||
backend.On("UpdateGroupName", mock.Anything, "g-1", "new").Return(nil)
|
||||
logger := log.NopLogger()
|
||||
g := Graph{BaseGraphService: BaseGraphService{logger: &logger}, auditEmitter: rec, identityBackend: backend}
|
||||
|
||||
r := httptest.NewRequest(http.MethodPatch, "/graph/v1.0/groups/g-1", strings.NewReader(`{"displayName":"new"}`))
|
||||
rctx := chi.NewRouteContext()
|
||||
rctx.URLParams.Add("groupID", "g-1")
|
||||
r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, rctx))
|
||||
w := httptest.NewRecorder()
|
||||
g.PatchGroup(w, r)
|
||||
|
||||
require.Equal(t, http.StatusNoContent, w.Code)
|
||||
require.Len(t, rec.events, 1, "a rename publishes no domain event, PatchGroup records it")
|
||||
ev := rec.events[0]
|
||||
assert.Equal(t, audit.GroupUpdate, ev.Definition)
|
||||
assert.Equal(t, "g-1", ev.Target.ID)
|
||||
assert.Equal(t, "old", ev.Target.Name, "a rename keeps the old name in the target")
|
||||
require.NotNil(t, ev.Change)
|
||||
assert.Equal(t, map[string]any{"displayname": "old"}, ev.Change.Before)
|
||||
assert.Equal(t, map[string]any{"displayname": "new"}, ev.Change.After)
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/render"
|
||||
"github.com/opencloud-eu/reva/v3/pkg/audit"
|
||||
revactx "github.com/opencloud-eu/reva/v3/pkg/ctx"
|
||||
"github.com/opencloud-eu/reva/v3/pkg/events"
|
||||
)
|
||||
@@ -176,11 +177,28 @@ func (g Graph) PatchGroup(w http.ResponseWriter, r *http.Request) {
|
||||
errorcode.InvalidRequest.Render(w, r, http.StatusBadRequest, "Invalid displayName")
|
||||
return
|
||||
}
|
||||
target := audit.Target{ID: groupID}
|
||||
var before map[string]any
|
||||
if audit.Enabled(g.auditEmitter) {
|
||||
// a rename keeps the old name in the target
|
||||
if group, err := g.identityBackend.GetGroup(r.Context(), groupID, nil); err == nil {
|
||||
target.Name = group.GetDisplayName()
|
||||
before = map[string]any{"displayname": target.Name}
|
||||
}
|
||||
}
|
||||
if err := g.identityBackend.UpdateGroupName(r.Context(), groupID, displayName); err != nil {
|
||||
logger.Debug().Err(err).Msg("could not update group displayName")
|
||||
errorcode.RenderError(w, r, err)
|
||||
return
|
||||
}
|
||||
// renames publish no domain event, so they are audited here
|
||||
if err := g.emitAudit(r.Context(), audit.Event{
|
||||
Definition: audit.GroupUpdate,
|
||||
Target: target,
|
||||
Change: &audit.Change{Before: before, After: map[string]any{"displayname": displayName}},
|
||||
}); err != nil {
|
||||
logger.Error().Err(err).Msg("could not emit audit event")
|
||||
}
|
||||
}
|
||||
|
||||
if memberRefs, ok := changes.GetMembersodataBindOk(); ok {
|
||||
|
||||
@@ -208,7 +208,7 @@ func Server(cfg *config.Config) *cobra.Command {
|
||||
logger.Error().Err(err).Msg("Error initializing the audit emitter")
|
||||
return err
|
||||
}
|
||||
defer auditemitter.Close(auditEmitter)
|
||||
defer audit.CloseEmitter(auditEmitter)
|
||||
|
||||
lh := staticroutes.StaticRouteHandler{
|
||||
Prefix: cfg.HTTP.Root,
|
||||
@@ -297,9 +297,15 @@ func newOIDCAuthenticator(logger log.Logger, cfg *config.Config, userInfoCache m
|
||||
logger.Warn().Msg("OIDC access token audience validation is disabled. Configure PROXY_OIDC_AUDIENCES to enable it; this is recommended for production.")
|
||||
}
|
||||
|
||||
var loginStore microstore.Store
|
||||
if cfg.Audit.Enabled {
|
||||
loginStore = auditLoginStore(cfg)
|
||||
}
|
||||
|
||||
return middleware.NewOIDCAuthenticator(
|
||||
middleware.Logger(logger),
|
||||
middleware.UserInfoCache(userInfoCache),
|
||||
middleware.AuditLoginStore(loginStore),
|
||||
middleware.DefaultAccessTokenTTL(cfg.OIDC.UserinfoCache.TTL),
|
||||
middleware.HTTPClient(httpClient),
|
||||
middleware.OIDCIss(cfg.OIDC.Issuer),
|
||||
@@ -310,6 +316,25 @@ func newOIDCAuthenticator(logger log.Logger, cfg *config.Config, userInfoCache m
|
||||
), nil
|
||||
}
|
||||
|
||||
// auditLoginStore keeps the OIDC sessions already recorded as logins in the
|
||||
// audit log. It uses the store of the userinfo cache, but a database of its
|
||||
// own: nats-js-kv only supports a TTL per database (bucket), and the one of the
|
||||
// userinfo cache is far shorter than a session.
|
||||
func auditLoginStore(cfg *config.Config) microstore.Store {
|
||||
c := cfg.OIDC.UserinfoCache
|
||||
return store.Create(
|
||||
store.Store(c.Store),
|
||||
store.TTL(middleware.AuditLoginTTL),
|
||||
microstore.Nodes(c.Nodes...),
|
||||
microstore.Database("audit-logins"),
|
||||
store.DisablePersistence(c.DisablePersistence),
|
||||
store.Authentication(c.AuthUsername, c.AuthPassword),
|
||||
store.TLSEnabled(c.EnableTLS),
|
||||
store.TLSInsecure(c.TLSInsecure),
|
||||
store.TLSRootCA(c.TLSRootCACertificate),
|
||||
)
|
||||
}
|
||||
|
||||
func loadMiddlewares(logger log.Logger, cfg *config.Config,
|
||||
userInfoCache, signingKeyStore microstore.Store,
|
||||
traceProvider trace.TracerProvider, metrics metrics.Metrics,
|
||||
|
||||
@@ -244,13 +244,13 @@ type ServiceAccount struct {
|
||||
ServiceAccountSecret string `yaml:"service_account_secret" env:"OC_SERVICE_ACCOUNT_SECRET;PROXY_SERVICE_ACCOUNT_SECRET" desc:"The service account secret." introductionVersion:"1.0.0"`
|
||||
}
|
||||
|
||||
// Events combines the configuration options for the event bus.
|
||||
// Audit configures the audit events of the service.
|
||||
type Audit struct {
|
||||
Enabled bool `yaml:"enabled" env:"OC_AUDIT_ENABLED;PROXY_AUDIT_ENABLED" desc:"Emit audit events for logins and failed logins to the audit stream." introductionVersion:"%%NEXT%%"`
|
||||
Enabled bool `yaml:"enabled" env:"OC_AUDIT_ENABLED;PROXY_AUDIT_ENABLED" desc:"Emit audit events for logins and failed logins, public link access and backchannel logouts to the audit stream." introductionVersion:"%%NEXT%%"`
|
||||
Mode string `yaml:"mode" env:"OC_AUDIT_MODE;PROXY_AUDIT_MODE" desc:"What happens when an audit event can't be stored. 'best_effort', the only mode for now, never blocks a request and counts dropped events." introductionVersion:"%%NEXT%%"`
|
||||
}
|
||||
|
||||
// Events combines the configuration options for the event bus.
|
||||
type Events struct {
|
||||
Endpoint string `yaml:"endpoint" env:"OC_EVENTS_ENDPOINT;PROXY_EVENTS_ENDPOINT" desc:"The address of the event system. The event system is the message queuing service. It is used as message broker for the microservice architecture. Set to a empty string to disable emitting events." introductionVersion:"1.0.0"`
|
||||
Cluster string `yaml:"cluster" env:"OC_EVENTS_CLUSTER;PROXY_EVENTS_CLUSTER" desc:"The clusterID of the event system. The event system is the message queuing service. It is used as message broker for the microservice architecture." introductionVersion:"1.0.0"`
|
||||
|
||||
@@ -99,6 +99,32 @@ func TestNewLoginNeedsAudit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// nats-js-kv only has a TTL per bucket: in the userinfo cache a login record
|
||||
// would expire with the cached tokens, after seconds instead of a day
|
||||
func TestNewLoginUsesTheLoginStore(t *testing.T) {
|
||||
client := tokenClient(t, map[string][2]string{
|
||||
"web-1": {"s-1", "web"},
|
||||
"web-2": {"s-1", "web"},
|
||||
})
|
||||
cache, logins := store.NewMemoryStore(), store.NewMemoryStore()
|
||||
a := NewOIDCAuthenticator(
|
||||
Logger(log.NopLogger()), OIDCClient(client), UserInfoCache(cache), AuditLoginStore(logins),
|
||||
SkipUserInfo(true), OIDCIss("https://idp.example.org"), AuditEmitter(newRecordingEmitter()),
|
||||
)
|
||||
|
||||
_, first := authenticate(t, a, "web-1")
|
||||
_, renewed := authenticate(t, a, "web-2")
|
||||
|
||||
assert.True(t, first)
|
||||
assert.False(t, renewed)
|
||||
records, err := logins.Read(loginKey("s-1", "web"))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, records, 1)
|
||||
assert.Equal(t, AuditLoginTTL, records[0].Expiry.Round(time.Hour))
|
||||
_, err = cache.Read(loginKey("s-1", "web"))
|
||||
assert.ErrorIs(t, err, store.ErrNotFound, "no login records in the userinfo cache")
|
||||
}
|
||||
|
||||
func TestLoginKeyIsNotFoundByTheBackchannelLogout(t *testing.T) {
|
||||
cache := store.NewMemoryStore()
|
||||
sessionKey, err := bcl.NewKey("alice", "s-1")
|
||||
|
||||
@@ -32,9 +32,15 @@ const (
|
||||
func NewOIDCAuthenticator(opts ...Option) *OIDCAuthenticator {
|
||||
options := newOptions(opts...)
|
||||
|
||||
loginStore := options.AuditLoginStore
|
||||
if loginStore == nil {
|
||||
loginStore = options.UserInfoCache
|
||||
}
|
||||
|
||||
return &OIDCAuthenticator{
|
||||
Logger: options.Logger,
|
||||
userInfoCache: options.UserInfoCache,
|
||||
loginStore: loginStore,
|
||||
HTTPClient: options.HTTPClient,
|
||||
OIDCIss: options.OIDCIss,
|
||||
DefaultTokenCacheTTL: options.DefaultAccessTokenTTL,
|
||||
@@ -58,7 +64,9 @@ type OIDCAuthenticator struct {
|
||||
skipUserInfo bool
|
||||
// auditLogins makes the authenticator tell new logins from renewed tokens
|
||||
auditLogins bool
|
||||
TimeFunc func() time.Time
|
||||
// loginStore keeps the sessions already recorded as logins
|
||||
loginStore store.Store
|
||||
TimeFunc func() time.Time
|
||||
}
|
||||
|
||||
func (m *OIDCAuthenticator) getClaims(token string, req *http.Request) (map[string]any, bool, error) {
|
||||
@@ -262,10 +270,11 @@ func (m *OIDCAuthenticator) Authenticate(r *http.Request) AuthenticationResult {
|
||||
return Succeeded(r.WithContext(oidc.NewContext(ctx, claims)))
|
||||
}
|
||||
|
||||
// loginTTL is how long a session counts as logged in for the audit log. It
|
||||
// only has to outlive the session at the identity provider; a session that
|
||||
// lasts longer is recorded as a new login once a day.
|
||||
const loginTTL = 24 * time.Hour
|
||||
// AuditLoginTTL is how long a session counts as logged in for the audit log.
|
||||
// It only has to outlive the session at the identity provider; a session that
|
||||
// lasts longer is recorded as a new login once a day. Stores that only support
|
||||
// a TTL per bucket, like nats-js-kv, need it as the TTL of the login store.
|
||||
const AuditLoginTTL = 24 * time.Hour
|
||||
|
||||
// newLogin reports whether a new access token starts a login for the audit
|
||||
// log. A token with a session ID, as Keycloak issues them, renews the session
|
||||
@@ -277,14 +286,14 @@ func (m *OIDCAuthenticator) newLogin(claims map[string]any) bool {
|
||||
return true
|
||||
}
|
||||
key := loginKey(sid, oidcClientID(claims))
|
||||
records, err := m.userInfoCache.Read(key)
|
||||
records, err := m.loginStore.Read(key)
|
||||
switch {
|
||||
case err == nil && len(records) > 0:
|
||||
return false
|
||||
case err != nil && !errors.Is(err, store.ErrNotFound):
|
||||
m.Logger.Error().Err(err).Msg("could not read the login record, recording a login")
|
||||
}
|
||||
if err := m.userInfoCache.Write(&store.Record{Key: key, Value: []byte{1}, Expiry: loginTTL}); err != nil {
|
||||
if err := m.loginStore.Write(&store.Record{Key: key, Value: []byte{1}, Expiry: AuditLoginTTL}); err != nil {
|
||||
m.Logger.Error().Err(err).Msg("could not write the login record")
|
||||
}
|
||||
return true
|
||||
|
||||
@@ -26,6 +26,9 @@ type Option func(o *Options)
|
||||
type Options struct {
|
||||
// AuditEmitter reports logins and failed logins
|
||||
AuditEmitter audit.Emitter
|
||||
// AuditLoginStore keeps the OIDC sessions already recorded as logins, the
|
||||
// UserInfoCache if not set
|
||||
AuditLoginStore store.Store
|
||||
// Logger to use for logging, must be set
|
||||
Logger log.Logger
|
||||
// PolicySelectorConfig for using the policy selector
|
||||
@@ -284,7 +287,6 @@ func TenantIDMappingEnabled(val bool) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// EventsPublisher sets the events publisher.
|
||||
// AuditEmitter sets the emitter for audit events.
|
||||
func AuditEmitter(e audit.Emitter) Option {
|
||||
return func(o *Options) {
|
||||
@@ -292,6 +294,13 @@ func AuditEmitter(e audit.Emitter) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// AuditLoginStore sets the store for the OIDC sessions already recorded as logins.
|
||||
func AuditLoginStore(s store.Store) Option {
|
||||
return func(o *Options) {
|
||||
o.AuditLoginStore = s
|
||||
}
|
||||
}
|
||||
|
||||
// EventsPublisher sets the events publisher.
|
||||
func EventsPublisher(ep events.Publisher) Option {
|
||||
return func(o *Options) {
|
||||
|
||||
Reference in new issue
Block a user