diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 7ca1c94c6..33aad61e1 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -69,3 +69,10 @@ jobs: psql -h localhost --user postgres -d batondb -t -c "SELECT attr_first_name, attr_job_title FROM users WHERE username = 'jane.doe'" | grep -q "Janet.*Senior Software Engineer" env: PGPASSWORD: secretpassword + # Uses the baton CLI that the sync-test action installs. + - name: Run event feed smoke test + run: test/event_feed_smoke.sh postgres + env: + PGPASSWORD: secretpassword + CHANGED_USER: jane.doe + SQL_CMD: psql -h localhost --user postgres -d batondb -t -A diff --git a/README.md b/README.md index d188d9040..a1ca0dfec 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,18 @@ Resource types and grants queries can define an `event_feed` section so Conducto The overlap window re-reads recent rows so rows with tied or late-committed timestamps are not missed. Re-read rows produce the same event IDs, and ConductorOne ignores the duplicates. Resource types with an `event_feed` also need a `get` query that uses `?`. See [`examples/example.yml`](examples/example.yml) for a complete configuration. +The cursor column (for example `updated_at`) must change on every insert and update, including updates made by provisioning and actions. Use a trigger or an `ON UPDATE` default; otherwise every writer has to set it explicitly. + +#### Grant revokes and soft deletes + +A grants `event_feed` reports revokes through `revokes_query`, which can only see rows that are soft-deleted (for example, rows with a `deleted_at` timestamp). A hard `DELETE` leaves nothing to read, so the revoke is only picked up at the next full sync. If your table hard-deletes, add a soft-delete column or an audit table filled by a trigger. When you configure `revokes_query`: + +- The full-sync grants `query` must exclude soft-deleted rows (for example `WHERE deleted_at IS NULL`). Otherwise every full sync restores the grants the feed revoked. +- Revoke provisioning must soft-delete the row (set `deleted_at` and `updated_at`) instead of deleting it. +- Grant provisioning must revive a soft-deleted row (clear `deleted_at`, update `updated_at`) instead of inserting a duplicate or doing nothing. + +The test examples (`postgres-test.yml`, `sqlserver-test.yml`, `mysql-test.yml`, `vertica-test.yml`) follow these rules, and `test/event_feed_smoke.sh` checks them against the matching `test/*-init.sql` database. + **Multi-database limitation:** event feed queries and `get` queries run only against the primary database (the lexicographically first one), even when `connect.databases` is configured. Full syncs still cover every database, but between full syncs: - Changes in any other database produce no events. diff --git a/baton_capabilities.json b/baton_capabilities.json index f6d9c357b..f41721f54 100644 --- a/baton_capabilities.json +++ b/baton_capabilities.json @@ -12,6 +12,7 @@ }, "capabilities": [ "CAPABILITY_SYNC", + "CAPABILITY_TARGETED_SYNC", "CAPABILITY_PROVISION" ], "permissions": {} @@ -19,7 +20,10 @@ ], "connectorCapabilities": [ "CAPABILITY_PROVISION", - "CAPABILITY_SYNC" + "CAPABILITY_SYNC", + "CAPABILITY_TARGETED_SYNC", + "CAPABILITY_EVENT_FEED_V2", + "CAPABILITY_SERVICE_MODE_TARGETED_SYNC" ], "credentialDetails": {} } \ No newline at end of file diff --git a/examples/example.yml b/examples/example.yml index 472d2738b..37e3a6864 100644 --- a/examples/example.yml +++ b/examples/example.yml @@ -135,16 +135,27 @@ resource_types: vars: user_id: "principal.ID" access_level: "'basic'" + # Grant revives a soft-deleted row, or inserts a new one. Upsert syntax depends on + # the database (e.g. ON CONFLICT in PostgreSQL, MERGE in SQL Server or Oracle). grant: queries: + - | + UPDATE user_access + SET deleted_at = NULL, updated_at = CURRENT_TIMESTAMP + WHERE user_id = ? AND level = ? AND deleted_at IS NOT NULL - | INSERT INTO user_access (user_id, level) - VALUES (?, ?) + SELECT ?, ? FROM DUAL + WHERE NOT EXISTS ( + SELECT 1 FROM user_access WHERE user_id = ? AND level = ? + ) + # Revoke soft-deletes so the grants event feed's revokes_query can report it. revoke: queries: - | - DELETE FROM user_access - WHERE user_id = ? + UPDATE user_access + SET deleted_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP + WHERE user_id = ? AND deleted_at IS NULL # Grants Query Configuration # -------------------------- @@ -157,6 +168,7 @@ resource_types: access_level, updated_at FROM user_access + WHERE deleted_at IS NULL LIMIT ? OFFSET ? map: - skip_if: ".access_level != 'basic'" @@ -183,9 +195,12 @@ resource_types: AND updated_at >= ? ORDER BY updated_at ASC, id ASC LIMIT ? OFFSET ? + # updated_at must change on every insert and update (a trigger or ON UPDATE default). changes_cursor_column: updated_at - # Optional: only configure when soft-delete is available in the schema. + # Optional: only configure when the table soft-deletes rows. Hard deletes can't be + # detected. When set, the full-sync grants query must exclude soft-deleted rows, revoke + # must soft-delete, and grant must revive a soft-deleted row (see provisioning above). revokes_query: | SELECT id AS grant_id, user_id, access_level, deleted_at FROM user_access diff --git a/examples/mysql-test.yml b/examples/mysql-test.yml index b10576594..4fd322fe0 100644 --- a/examples/mysql-test.yml +++ b/examples/mysql-test.yml @@ -434,11 +434,13 @@ resource_types: user_roles ur ON u.id = ur.user_id JOIN roles r ON r.id = ur.role_id + WHERE + ur.deleted_at IS NULL pagination: strategy: "offset" primary_key: "username" map: - - skip_if: ".role_name != resource.ID" + - skip_if: "string(.role_name) != resource.ID" principal_id: ".username" principal_type: "user" entitlement_id: "member" diff --git a/examples/postgres-test-exclusion-group.yml b/examples/postgres-test-exclusion-group.yml index 9350ffb39..14ad9207d 100644 --- a/examples/postgres-test-exclusion-group.yml +++ b/examples/postgres-test-exclusion-group.yml @@ -398,6 +398,7 @@ resource_types: JOIN roles r ON r.id = ur.role_id WHERE u.username = ? + AND ur.deleted_at IS NULL map: - principal_id: ".username" principal_type: "user" @@ -423,7 +424,9 @@ resource_types: FROM users u, roles r WHERE u.username = ? AND r.role_name = ? - ON CONFLICT (user_id, role_id) DO NOTHING + ON CONFLICT (user_id, role_id) DO UPDATE + SET deleted_at = NULL, updated_at = CURRENT_TIMESTAMP + WHERE user_roles.deleted_at IS NOT NULL revoke: validation_queries: - | @@ -456,6 +459,8 @@ resource_types: user_roles ur ON u.id = ur.user_id JOIN roles r ON r.id = ur.role_id + WHERE + ur.deleted_at IS NULL pagination: strategy: "offset" primary_key: "username" diff --git a/examples/postgres-test.yml b/examples/postgres-test.yml index 2a6e019df..3319402a7 100644 --- a/examples/postgres-test.yml +++ b/examples/postgres-test.yml @@ -489,7 +489,9 @@ resource_types: FROM users u, roles r WHERE u.username = ? AND r.role_name = ? - ON CONFLICT (user_id, role_id) DO NOTHING + ON CONFLICT (user_id, role_id) DO UPDATE + SET deleted_at = NULL, updated_at = CURRENT_TIMESTAMP + WHERE user_roles.deleted_at IS NOT NULL revoke: validation_queries: - | @@ -499,16 +501,18 @@ resource_types: FROM users u, roles r WHERE u.username = ? AND r.role_name = ? + # Soft delete so the event feed's revokes_query can report the revoke. queries: - | - DELETE FROM user_roles + UPDATE user_roles + SET deleted_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP WHERE user_id IN ( SELECT id FROM users WHERE username = ? ) AND role_id IN ( SELECT id FROM roles WHERE role_name = ? - ) + ) AND deleted_at IS NULL # Dynamic grants based on SQL queries to associate users with roles grants: @@ -522,6 +526,8 @@ resource_types: user_roles ur ON u.id = ur.user_id JOIN roles r ON r.id = ur.role_id + WHERE + ur.deleted_at IS NULL pagination: strategy: "offset" primary_key: "username" diff --git a/examples/sqlserver-test.yml b/examples/sqlserver-test.yml index 215f2ca1a..7ffc9c0c0 100644 --- a/examples/sqlserver-test.yml +++ b/examples/sqlserver-test.yml @@ -407,8 +407,18 @@ resource_types: vars: username: "principal.ID" role_name: "resource.ID" + # Revives a soft-deleted assignment, or inserts a new one. grant: queries: + - | + UPDATE ur + SET IsDeleted = 0, DeletedAt = NULL, UpdatedAt = SYSUTCDATETIME() + FROM UserRoles ur + INNER JOIN Users u ON ur.UserID = u.UserID + INNER JOIN Roles r ON ur.RoleID = r.RoleID + WHERE u.Username = ? + AND r.RoleName = ? + AND ur.IsDeleted = 1 - | INSERT INTO UserRoles ( UserID, @@ -420,14 +430,22 @@ resource_types: FROM Users u, Roles r WHERE u.Username = ? AND r.RoleName = ? + AND NOT EXISTS ( + SELECT 1 FROM UserRoles ur + WHERE ur.UserID = u.UserID AND ur.RoleID = r.RoleID + ) + # Soft delete so the event feed's revokes_query can report the revoke. revoke: queries: - | - DELETE ur FROM UserRoles ur + UPDATE ur + SET IsDeleted = 1, DeletedAt = SYSUTCDATETIME(), UpdatedAt = SYSUTCDATETIME() + FROM UserRoles ur INNER JOIN Users u ON ur.UserID = u.UserID INNER JOIN Roles r ON ur.RoleID = r.RoleID WHERE u.Username = ? AND r.RoleName = ? + AND ur.IsDeleted = 0 # Grant discovery for existing role assignments grants: @@ -438,6 +456,7 @@ resource_types: FROM UserRoles ur INNER JOIN Users u ON ur.UserID = u.UserID INNER JOIN Roles r ON ur.RoleID = r.RoleID + WHERE ur.IsDeleted = 0 ORDER BY r.RoleID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY map: diff --git a/examples/vertica-test.yml b/examples/vertica-test.yml index 3d8da66ff..73b11bbc1 100644 --- a/examples/vertica-test.yml +++ b/examples/vertica-test.yml @@ -72,7 +72,8 @@ resource_types: LEFT JOIN users m ON u.manager_id = m.id WHERE u.username = ? - # Detects new and modified users via updated_at. + # Detects new and modified users via updated_at. Vertica has no triggers, so anything + # that writes to these tables must set updated_at (and deleted_at on revoke) itself. event_feed: query: | SELECT @@ -158,6 +159,8 @@ resource_types: user_roles ur ON u.id = ur.user_id JOIN roles r ON r.id = ur.role_id + WHERE + ur.deleted_at IS NULL pagination: strategy: "offset" primary_key: "username" diff --git a/test/event_feed_smoke.sh b/test/event_feed_smoke.sh new file mode 100755 index 000000000..cf5ee55ec --- /dev/null +++ b/test/event_feed_smoke.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +# Smoke test for the event feed of the shipped examples against a freshly loaded test database. +# +# Usage: test/event_feed_smoke.sh +# +# Environment: +# BATON_SQL path to the connector binary (default: ./baton-sql) +# BATON_CONFIG_PATH example config for the engine, plus the DB_* variables it reads +# SQL_CMD command that reads one SQL statement on stdin and prints the result rows. +# Required for engines whose example provisions role grants. +# CHANGED_USER optional user whose row was updated before running; the feed must report it. +set -euo pipefail + +ENGINE="${1:?usage: $0 }" +BATON_SQL="${BATON_SQL:-./baton-sql}" +WORKDIR="$(mktemp -d)" +trap 'rm -rf "$WORKDIR"' EXIT + +# Seeded soft-deleted assignment, and a live assignment to revoke and grant again. +SEEDED_USER="disabled.user" +SEEDED_ROLE="reader" +LIVE_USER="service.acct" +LIVE_ROLE="user" + +case "$ENGINE" in + postgres | mysql | vertica) + HAS_GRANTS_FEED=1 + deleted_at_sql="SELECT CASE WHEN ur.deleted_at IS NULL THEN 'live' ELSE 'deleted' END FROM user_roles ur JOIN users u ON u.id = ur.user_id JOIN roles r ON r.id = ur.role_id WHERE u.username = '$LIVE_USER' AND r.role_name = '$LIVE_ROLE'" + ;; + sqlserver) + HAS_GRANTS_FEED=1 + deleted_at_sql="SELECT CASE WHEN ur.IsDeleted = 0 AND ur.DeletedAt IS NULL THEN 'live' ELSE 'deleted' END FROM UserRoles ur JOIN Users u ON u.UserID = ur.UserID JOIN Roles r ON r.RoleID = ur.RoleID WHERE u.Username = '$LIVE_USER' AND r.RoleName = '$LIVE_ROLE'" + ;; + oracle) + HAS_GRANTS_FEED=0 + ;; + *) + echo "unknown engine: $ENGINE" >&2 + exit 2 + ;; +esac + +case "$ENGINE" in + postgres | sqlserver) HAS_ROLE_PROVISIONING=1 ;; + *) HAS_ROLE_PROVISIONING=0 ;; +esac + +fail() { + echo "FAIL: $*" >&2 + exit 1 +} + +run_feed() { + local out="$WORKDIR/feed.json" + "$BATON_SQL" --event-feed=true --event-feed-id=sql_event_feed --log-level=error >"$out" || + fail "event feed exited with $?" + echo "$out" +} + +# protojson randomly adds a space after ':' and ',', so the patterns allow an optional one. +has_event() { + local file="$1" kind="$2" role="$3" user="$4" + grep "\"$kind\"" "$file" | grep -E "\"resource\": ?\"$role\"" | + grep -qE "\"resourceType\": ?\"user\", ?\"resource\": ?\"$user\"" +} + +run_sync() { + local c1z="$WORKDIR/sync.c1z" + rm -f "$c1z" + "$BATON_SQL" -f "$c1z" --log-level=error >/dev/null 2>&1 || fail "full sync exited with $?" + echo "$c1z" +} + +synced_grant() { + synced_grant_id "$1" "role:$LIVE_ROLE:member:user:$LIVE_USER" +} + +synced_grant_id() { + local grants="$WORKDIR/grants.json" + baton grants -f "$1" -o json >"$grants" || fail "baton grants exited with $?" + grep -q "\"$2\"" "$grants" +} + +db_state() { + echo "$deleted_at_sql" | $SQL_CMD | awk 'NF { print $1; exit }' +} + +echo "== feed runs and reports seeded changes" +feed="$(run_feed)" +grep -q '"resourceChangeEvent"' "$feed" || fail "no resource change events" +if [ -n "${CHANGED_USER:-}" ]; then + grep '"resourceChangeEvent"' "$feed" | grep -qE "\"resourceType\": ?\"user\", ?\"resource\": ?\"$CHANGED_USER\"" || + fail "no resource change event for $CHANGED_USER" +fi +if [ "$HAS_GRANTS_FEED" = 1 ]; then + has_event "$feed" createRevokeEvent "$SEEDED_ROLE" "$SEEDED_USER" || fail "no revoke event for seeded $SEEDED_USER/$SEEDED_ROLE" + has_event "$feed" createGrantEvent "$SEEDED_ROLE" "$SEEDED_USER" && fail "grant event for soft-deleted $SEEDED_USER/$SEEDED_ROLE" + c1z="$(run_sync)" + synced_grant_id "$c1z" "role:$SEEDED_ROLE:member:user:$SEEDED_USER" && + fail "full sync returned soft-deleted grant $SEEDED_USER/$SEEDED_ROLE" +fi + +if [ "$HAS_ROLE_PROVISIONING" = 0 ]; then + echo "PASS ($ENGINE: feed only)" + exit 0 +fi +: "${SQL_CMD:?SQL_CMD is required for $ENGINE}" + +echo "== revoke through the connector soft-deletes" +c1z="$(run_sync)" +synced_grant "$c1z" || fail "expected live grant $LIVE_USER/$LIVE_ROLE before revoke" +"$BATON_SQL" -f "$c1z" --revoke-grant="role:$LIVE_ROLE:member:user:$LIVE_USER" --log-level=error >/dev/null 2>&1 || + fail "revoke failed" +[ "$(db_state)" = "deleted" ] || fail "row for $LIVE_USER/$LIVE_ROLE is not soft-deleted" +"$BATON_SQL" -f "$c1z" --revoke-grant="role:$LIVE_ROLE:member:user:$LIVE_USER" --log-level=error >/dev/null 2>&1 || + fail "revoking an already revoked grant failed" +feed="$(run_feed)" +has_event "$feed" createRevokeEvent "$LIVE_ROLE" "$LIVE_USER" || fail "no revoke event after revoke" +has_event "$feed" createGrantEvent "$LIVE_ROLE" "$LIVE_USER" && fail "grant event after revoke" + +echo "== full sync keeps it revoked" +c1z="$(run_sync)" +synced_grant "$c1z" && fail "full sync restored revoked grant" + +echo "== grant through the connector revives the row" +"$BATON_SQL" -f "$c1z" --grant-entitlement="role:$LIVE_ROLE:member" --grant-principal="$LIVE_USER" \ + --grant-principal-type=user --log-level=error >/dev/null 2>&1 || fail "grant failed" +[ "$(db_state)" = "live" ] || fail "row for $LIVE_USER/$LIVE_ROLE was not revived" +"$BATON_SQL" -f "$c1z" --grant-entitlement="role:$LIVE_ROLE:member" --grant-principal="$LIVE_USER" \ + --grant-principal-type=user --log-level=error >/dev/null 2>&1 || fail "granting an already live grant failed" +feed="$(run_feed)" +has_event "$feed" createGrantEvent "$LIVE_ROLE" "$LIVE_USER" || fail "no grant event after grant" +has_event "$feed" createRevokeEvent "$LIVE_ROLE" "$LIVE_USER" && fail "revoke event after grant" +c1z="$(run_sync)" +synced_grant "$c1z" || fail "full sync is missing the granted $LIVE_USER/$LIVE_ROLE" + +echo "PASS ($ENGINE)" diff --git a/test/mysql-init.sql b/test/mysql-init.sql index 8fcd4e53f..57ed63e8f 100644 --- a/test/mysql-init.sql +++ b/test/mysql-init.sql @@ -27,7 +27,8 @@ CREATE TABLE users ( attr_division VARCHAR(100), attr_company VARCHAR(100), attr_employee_number VARCHAR(50), - attr_employment_type VARCHAR(50) + attr_employment_type VARCHAR(50), + updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6) ); -- Insert sample users with different date formats for last_login (without manager relationships) @@ -63,7 +64,8 @@ SELECT 'Manager relationships established' as message; -- Create roles table CREATE TABLE roles ( id INT AUTO_INCREMENT PRIMARY KEY, - role_name VARCHAR(100) NOT NULL + role_name VARCHAR(100) NOT NULL, + updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6) ); -- Insert sample roles @@ -74,8 +76,11 @@ INSERT INTO roles (role_name) VALUES -- Create user_roles table for many-to-many relationship CREATE TABLE user_roles ( + id INT AUTO_INCREMENT UNIQUE, user_id INT, role_id INT, + updated_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), + deleted_at TIMESTAMP(6) NULL, PRIMARY KEY (user_id, role_id), FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (role_id) REFERENCES roles(id) @@ -91,6 +96,10 @@ INSERT INTO user_roles (user_id, role_id) VALUES (6, 1), -- bjorn.tipling.c1 has admin role (7, 2); -- bjorn.tipling.ins has user role +-- Soft-deleted assignment (revoked an hour ago) so the event feed reports a revoke +INSERT INTO user_roles (user_id, role_id, updated_at, deleted_at) VALUES +(5, 3, CURRENT_TIMESTAMP(6) - INTERVAL 1 HOUR, CURRENT_TIMESTAMP(6) - INTERVAL 1 HOUR); -- disabled.user had reader role + -- Create table to track last login attempts (for testing date formats) CREATE TABLE login_history ( id INT AUTO_INCREMENT PRIMARY KEY, diff --git a/test/oracle-init.sql b/test/oracle-init.sql index 440243bf1..ae1307db7 100644 --- a/test/oracle-init.sql +++ b/test/oracle-init.sql @@ -13,6 +13,7 @@ GRANT CREATE SESSION TO baton; GRANT CREATE TABLE TO baton; GRANT CREATE SEQUENCE TO baton; GRANT CREATE VIEW TO baton; +GRANT CREATE TRIGGER TO baton; GRANT UNLIMITED TABLESPACE TO baton; GRANT DBA TO baton; -- For testing purposes, grant DBA access -- Grant access to DBA dictionary views (required for DBA_ROLES, DBA_USERS, etc.) @@ -80,9 +81,19 @@ CREATE TABLE users ( attr_division VARCHAR2(100), attr_company VARCHAR2(100), attr_employee_number VARCHAR2(50), - attr_employment_type VARCHAR2(50) + attr_employment_type VARCHAR2(50), + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL ); +-- Keep updated_at current on every update so the event feed sees the change +CREATE OR REPLACE TRIGGER users_set_updated_at +BEFORE UPDATE ON users +FOR EACH ROW +BEGIN + :NEW.updated_at := CURRENT_TIMESTAMP; +END; +/ + -- Insert sample users with attr_* data INSERT INTO users (username, email, employee_id, status, account_type, created_at, last_login, attr_first_name, attr_middle_name, attr_last_name, attr_display_name, attr_job_title, attr_department, attr_division, attr_company, attr_employee_number, attr_employment_type) VALUES ('admin', 'admin@example.com', 'EMP001', 'active', 'human', TIMESTAMP '2025-01-01 12:00:00', TIMESTAMP '2025-04-15 09:30:00', 'Admin', NULL, 'User', 'Admin User', 'System Administrator', 'IT', 'Technology', 'Example Corp', '10001', 'full_time'); diff --git a/test/postgres-init.sql b/test/postgres-init.sql index bab9dc848..ee12ddead 100644 --- a/test/postgres-init.sql +++ b/test/postgres-init.sql @@ -31,7 +31,8 @@ CREATE TABLE users ( attr_division VARCHAR(100), attr_company VARCHAR(100), attr_employee_number VARCHAR(50), - attr_employment_type VARCHAR(50) + attr_employment_type VARCHAR(50), + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ); -- Insert sample users with different date formats for last_login (without manager relationships) @@ -72,7 +73,8 @@ UPDATE users SET manager_id = (SELECT id FROM users WHERE username = 'robert.tab -- Create roles table CREATE TABLE roles ( id SERIAL PRIMARY KEY, - role_name VARCHAR(100) NOT NULL UNIQUE + role_name VARCHAR(100) NOT NULL UNIQUE, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ); -- Insert sample roles @@ -83,8 +85,11 @@ INSERT INTO roles (role_name) VALUES -- Create user_roles table for many-to-many relationship CREATE TABLE user_roles ( + id SERIAL UNIQUE, user_id INTEGER, role_id INTEGER, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + deleted_at TIMESTAMP NULL, PRIMARY KEY (user_id, role_id), FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (role_id) REFERENCES roles(id) @@ -103,6 +108,25 @@ INSERT INTO user_roles (user_id, role_id) VALUES (9, 2), -- robert.tables2 has user role (9, 1); -- robert.tables2 has admin role +-- Soft-deleted assignment (revoked an hour ago) so the event feed reports a revoke +INSERT INTO user_roles (user_id, role_id, updated_at, deleted_at) VALUES +(5, 3, CURRENT_TIMESTAMP - INTERVAL '1 hour', CURRENT_TIMESTAMP - INTERVAL '1 hour'); -- disabled.user had reader role + +-- Keep updated_at current on every update so the event feed sees the change +CREATE OR REPLACE FUNCTION set_updated_at() RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER users_set_updated_at BEFORE UPDATE ON users + FOR EACH ROW EXECUTE FUNCTION set_updated_at(); +CREATE TRIGGER roles_set_updated_at BEFORE UPDATE ON roles + FOR EACH ROW EXECUTE FUNCTION set_updated_at(); +CREATE TRIGGER user_roles_set_updated_at BEFORE UPDATE ON user_roles + FOR EACH ROW EXECUTE FUNCTION set_updated_at(); + -- Create table to track last login attempts (for testing date formats) CREATE TABLE login_history ( diff --git a/test/sqlserver-init.sql b/test/sqlserver-init.sql index 75f9a55cb..e50a83725 100644 --- a/test/sqlserver-init.sql +++ b/test/sqlserver-init.sql @@ -14,6 +14,7 @@ CREATE TABLE Users ( LastLogin DATETIME2 NULL, ManagerID INT NULL, PasswordHash VARBINARY(32) NULL, + UpdatedAt DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME(), FOREIGN KEY (ManagerID) REFERENCES Users(UserID) ); @@ -21,14 +22,19 @@ CREATE TABLE Users ( CREATE TABLE Roles ( RoleID INT IDENTITY(1,1) PRIMARY KEY, RoleName NVARCHAR(100) NOT NULL UNIQUE, - Description NVARCHAR(255) NOT NULL + Description NVARCHAR(255) NOT NULL, + UpdatedAt DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME() ); -- Create UserRoles junction table for many-to-many relationship CREATE TABLE UserRoles ( + UserRoleID INT IDENTITY(1,1) UNIQUE, UserID INT, RoleID INT, AssignedAt DATETIME2 DEFAULT GETDATE(), + UpdatedAt DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME(), + IsDeleted BIT NOT NULL DEFAULT 0, + DeletedAt DATETIME2 NULL, PRIMARY KEY (UserID, RoleID), FOREIGN KEY (UserID) REFERENCES Users(UserID) ON DELETE CASCADE, FOREIGN KEY (RoleID) REFERENCES Roles(RoleID) ON DELETE CASCADE @@ -107,6 +113,35 @@ INSERT INTO UserRoles (UserID, RoleID) VALUES ((SELECT UserID FROM Users WHERE Username = 'bob.developer'), (SELECT RoleID FROM Roles WHERE RoleName = 'developer')), ((SELECT UserID FROM Users WHERE Username = 'bob.developer'), (SELECT RoleID FROM Roles WHERE RoleName = 'user')); +-- Soft-deleted assignment (revoked an hour ago) so the event feed reports a revoke +INSERT INTO UserRoles (UserID, RoleID, UpdatedAt, IsDeleted, DeletedAt) VALUES +((SELECT UserID FROM Users WHERE Username = 'disabled.user'), (SELECT RoleID FROM Roles WHERE RoleName = 'reader'), + DATEADD(HOUR, -1, SYSUTCDATETIME()), 1, DATEADD(HOUR, -1, SYSUTCDATETIME())); +GO + +-- Keep UpdatedAt current on every update so the event feed sees the change. +-- SET NOCOUNT ON keeps the trigger's own UPDATE out of the caller's rows-affected count. +CREATE TRIGGER TR_Users_SetUpdatedAt ON Users AFTER UPDATE AS +BEGIN + SET NOCOUNT ON; + UPDATE t SET UpdatedAt = SYSUTCDATETIME() FROM Users t INNER JOIN inserted i ON t.UserID = i.UserID; +END; +GO + +CREATE TRIGGER TR_Roles_SetUpdatedAt ON Roles AFTER UPDATE AS +BEGIN + SET NOCOUNT ON; + UPDATE t SET UpdatedAt = SYSUTCDATETIME() FROM Roles t INNER JOIN inserted i ON t.RoleID = i.RoleID; +END; +GO + +CREATE TRIGGER TR_UserRoles_SetUpdatedAt ON UserRoles AFTER UPDATE AS +BEGIN + SET NOCOUNT ON; + UPDATE t SET UpdatedAt = SYSUTCDATETIME() FROM UserRoles t INNER JOIN inserted i ON t.UserRoleID = i.UserRoleID; +END; +GO + -- Insert sample login history with various date formats INSERT INTO LoginHistory (UserID, LoginTime, LoginTimeText, LoginTimeAlt, LoginSuccess) VALUES ((SELECT UserID FROM Users WHERE Username = 'admin'), '2025-04-15 09:30:00', '15-APR-2025 09:30:00', '15/04/2025 09:30:00', 1), diff --git a/test/vertica-init.sql b/test/vertica-init.sql index 626c726c2..47d6cb79f 100644 --- a/test/vertica-init.sql +++ b/test/vertica-init.sql @@ -8,7 +8,8 @@ CREATE TABLE IF NOT EXISTS users ( account_type VARCHAR(20) DEFAULT 'human', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, last_login TIMESTAMP NULL, - manager_id INTEGER + manager_id INTEGER, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- Insert sample users @@ -27,7 +28,8 @@ UPDATE users SET manager_id = 3 WHERE username = 'disabled.user'; -- Create roles table CREATE TABLE IF NOT EXISTS roles ( id IDENTITY PRIMARY KEY, - role_name VARCHAR(100) NOT NULL + role_name VARCHAR(100) NOT NULL, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- Insert sample roles @@ -37,8 +39,11 @@ INSERT INTO roles (role_name) VALUES ('reader'); -- Create user_roles table CREATE TABLE IF NOT EXISTS user_roles ( + id IDENTITY, user_id INTEGER, role_id INTEGER, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + deleted_at TIMESTAMP NULL, PRIMARY KEY (user_id, role_id) ); @@ -49,4 +54,8 @@ INSERT INTO user_roles (user_id, role_id) VALUES (3, 2); INSERT INTO user_roles (user_id, role_id) VALUES (3, 3); INSERT INTO user_roles (user_id, role_id) VALUES (4, 2); +-- Soft-deleted assignment (revoked an hour ago) so the event feed reports a revoke +INSERT INTO user_roles (user_id, role_id, updated_at, deleted_at) +VALUES (5, 3, CURRENT_TIMESTAMP - INTERVAL '1 hour', CURRENT_TIMESTAMP - INTERVAL '1 hour'); + SELECT 'Vertica test database initialized successfully' AS message;