Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion deploy/clowdapp.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -948,7 +948,6 @@ objects:
- {name: GIN_MODE, value: '${GIN_MODE}'}
- {name: SENTRY_DSN, valueFrom: {secretKeyRef: {name: patchman-sentry, key: sentry-dsn}}}
- {name: DB_DEBUG, value: 'false'}
- {name: DB_USER, value: vmaas_sync}
- {name: SQL_JOB_FILE, value: '${SQL_JOB_FILE}'}
- {name: POD_CONFIG, value: '${SQL_JOB_CONFIG}'}

Expand Down
5 changes: 2 additions & 3 deletions docs/md/sql-jobs.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ reuse. Leaving a file selected reruns it on subsequent deployments. Kubernetes
may also retry failed pods. Script authors must make scripts idempotent or
document when reruns are safe, and operators must clear the selection when done.

The job uses the `vmaas_sync` database role and primary database. Scripts are
limited to that role's permissions. Do not grant admin access just to make a
script work. Schema changes belong in database migrations.
The job uses the database admin role and the primary database. Schema changes
belong in database migrations.

## Execution contract

Expand Down
46 changes: 46 additions & 0 deletions tasks/sql_job/sql/002_update_strings_sha512.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
-- Replace SHA-256 strings.id values with SHA-512 of strings.value.
--
-- Run only after every vmaas_sync writer stores SHA-512. A writer still hashing
-- with SHA-256 can point package rows back at ids this script removes.
-- Idempotent: a second run changes nothing once every id is 64 bytes.
-- Rewrites every package row that still points at a 32-byte id. The SQL job
-- holds those locks until the transaction commits.
--
-- Verify afterward. Both counts must be 0:
-- SELECT count(*) FROM strings WHERE octet_length(id) = 32;
-- SELECT count(*) FROM package
-- WHERE octet_length(description_hash) = 32
-- OR octet_length(summary_hash) = 32;

CREATE INDEX IF NOT EXISTS package_description_hash_idx ON package (description_hash);
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
CREATE INDEX IF NOT EXISTS package_summary_hash_idx ON package (summary_hash);

Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
INSERT INTO strings (id, value)
SELECT sha512(convert_to(s.value, 'UTF8')), s.value
FROM strings s
WHERE octet_length(s.id) = 32
AND EXISTS (
SELECT 1
FROM package p
WHERE p.description_hash = s.id
OR p.summary_hash = s.id
)
ON CONFLICT (id) DO NOTHING;

UPDATE package p
SET description_hash = sha512(convert_to(s.value, 'UTF8'))
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
FROM strings s
WHERE p.description_hash = s.id
AND octet_length(description_hash) = 32;

UPDATE package p
SET summary_hash = sha512(convert_to(s.value, 'UTF8'))
FROM strings s
WHERE p.summary_hash = s.id
AND octet_length(summary_hash) = 32;

DELETE FROM strings
WHERE octet_length(id) = 32;
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved

DROP INDEX IF EXISTS package_description_hash_idx;
DROP INDEX IF EXISTS package_summary_hash_idx;
2 changes: 1 addition & 1 deletion tasks/sql_job/sql_job.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func run() error {
if err != nil {
return err
}
core.ConfigureApp()
core.ConfigureAdminApp()
lockTimeout := time.Duration(utils.PodConfig.GetInt("sql_lock_timeout_seconds", 30)) * time.Second
statementTimeout := time.Duration(utils.PodConfig.GetInt("sql_statement_timeout_seconds", 1500)) * time.Second
ctx, cancel := context.WithTimeout(base.Context, statementTimeout)
Expand Down
28 changes: 28 additions & 0 deletions tasks/sql_job/sql_job_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,34 @@ func TestRunInvalidScript(t *testing.T) {
require.Error(t, run())
}

func TestRunUsesAdminRole(t *testing.T) {
utils.SkipWithoutDB(t)
// Save original credentials
origUser := utils.CoreCfg.DBUser
origPass := utils.CoreCfg.DBPassword
t.Cleanup(func() {
utils.CoreCfg.DBUser = origUser
utils.CoreCfg.DBPassword = origPass
database.Configure()
})
// App-user credentials must not be able to satisfy the job. Admin credentials stay valid.
utils.CoreCfg.DBUser = "not-the-admin"
utils.CoreCfg.DBPassword = "wrong"
require.NotEmpty(t, utils.CoreCfg.DBAdminUser)
require.NotEmpty(t, utils.CoreCfg.DBAdminPassword)
require.NotEqual(t, utils.CoreCfg.DBAdminUser, utils.CoreCfg.DBUser)

wd, err := os.Getwd()
require.NoError(t, err)
t.Chdir(filepath.Join(wd, "..", ".."))
t.Setenv("SQL_JOB_FILE", "000_test.sql")
require.NoError(t, run())

var current string
require.NoError(t, database.TestDB().Raw("SELECT current_user").Scan(&current).Error)
assert.Equal(t, utils.CoreCfg.DBAdminUser, current)
}

func TestReadScript(t *testing.T) {
dir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(dir, "valid.sql"), []byte("SELECT 1; SELECT 2;"), 0600))
Expand Down
18 changes: 11 additions & 7 deletions tasks/vmaas_sync/package_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"app/base/utils"
"app/base/vmaas"
"app/tasks"
"crypto/sha256"
"crypto/sha512"
"net/http"
"time"

Expand Down Expand Up @@ -49,12 +49,16 @@ type nameIDandEvra struct {
Evra string
}

func contentHash(str string) [sha512.Size]byte {
return sha512.Sum512([]byte(str))
}

func stringPtr2Hash(str *string) *[]byte {
if str == nil || *str == "" {
return nil
}
bytes32 := sha256.Sum256([]byte(*str))
bytes := bytes32[:]
sum := contentHash(*str)
bytes := sum[:]
return &bytes
}

Expand Down Expand Up @@ -129,17 +133,17 @@ func storePkgListData(vmaasData []vmaas.PkgListItem) error {
}

func storeStringsFromPkgListItems(tx *gorm.DB, vmaasData []vmaas.PkgListItem) error {
stringMap := make(map[[32]byte]string, len(vmaasData))
stringMap := make(map[[sha512.Size]byte]string, len(vmaasData))
for _, pkgListItem := range vmaasData {
stringMap[sha256.Sum256([]byte(pkgListItem.Description))] = pkgListItem.Description
stringMap[sha256.Sum256([]byte(pkgListItem.Summary))] = pkgListItem.Summary
stringMap[contentHash(pkgListItem.Description)] = pkgListItem.Description
stringMap[contentHash(pkgListItem.Summary)] = pkgListItem.Summary
}

strings := make([]models.String, 0, len(stringMap))
for key, v := range stringMap {
// need to allocate here, otherwise the slice references will point to stack space occupied by last element from
// iteration.
keySlice := make([]byte, 32)
keySlice := make([]byte, sha512.Size)
copy(keySlice, key[:])
if v != "" {
// don't store empty strings
Expand Down
12 changes: 12 additions & 0 deletions tasks/vmaas_sync/package_sync_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,24 @@ import (
"app/base/database"
"app/base/models"
"app/base/utils"
"crypto/sha512"
"testing"
"time"

"github.com/stretchr/testify/assert"
)

func TestStringPtr2HashSHA512(t *testing.T) {
value := "package summary"
got := stringPtr2Hash(&value)
sum := sha512.Sum512([]byte(value))
assert.Equal(t, sum[:], *got)

assert.Nil(t, stringPtr2Hash(nil))
empty := ""
assert.Nil(t, stringPtr2Hash(&empty))
}

func TestPkgListSyncPackages(t *testing.T) {
utils.SkipWithoutDB(t)
core.SetupTestEnvironment()
Expand Down
Loading