code.gitea.io/gitea@v1.21.7/models/migrations/v1_19/v233_test.go (about) 1 // Copyright 2022 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package v1_19 //nolint 5 6 import ( 7 "testing" 8 9 "code.gitea.io/gitea/models/migrations/base" 10 "code.gitea.io/gitea/modules/json" 11 "code.gitea.io/gitea/modules/secret" 12 "code.gitea.io/gitea/modules/setting" 13 webhook_module "code.gitea.io/gitea/modules/webhook" 14 15 "github.com/stretchr/testify/assert" 16 ) 17 18 func Test_AddHeaderAuthorizationEncryptedColWebhook(t *testing.T) { 19 // Create Webhook table 20 type Webhook struct { 21 ID int64 `xorm:"pk autoincr"` 22 Type webhook_module.HookType `xorm:"VARCHAR(16) 'type'"` 23 Meta string `xorm:"TEXT"` // store hook-specific attributes 24 25 // HeaderAuthorizationEncrypted should be accessed using HeaderAuthorization() and SetHeaderAuthorization() 26 HeaderAuthorizationEncrypted string `xorm:"TEXT"` 27 } 28 29 type ExpectedWebhook struct { 30 ID int64 `xorm:"pk autoincr"` 31 Meta string 32 HeaderAuthorization string 33 } 34 35 type HookTask struct { 36 ID int64 `xorm:"pk autoincr"` 37 HookID int64 38 PayloadContent string `xorm:"LONGTEXT"` 39 } 40 41 // Prepare and load the testing database 42 x, deferable := base.PrepareTestEnv(t, 0, new(Webhook), new(ExpectedWebhook), new(HookTask)) 43 defer deferable() 44 if x == nil || t.Failed() { 45 return 46 } 47 48 if err := AddHeaderAuthorizationEncryptedColWebhook(x); err != nil { 49 assert.NoError(t, err) 50 return 51 } 52 53 expected := []ExpectedWebhook{} 54 if err := x.Table("expected_webhook").Asc("id").Find(&expected); !assert.NoError(t, err) { 55 return 56 } 57 58 got := []Webhook{} 59 if err := x.Table("webhook").Select("id, meta, header_authorization_encrypted").Asc("id").Find(&got); !assert.NoError(t, err) { 60 return 61 } 62 63 for i, e := range expected { 64 assert.Equal(t, e.Meta, got[i].Meta) 65 66 if e.HeaderAuthorization == "" { 67 assert.Equal(t, "", got[i].HeaderAuthorizationEncrypted) 68 } else { 69 cipherhex := got[i].HeaderAuthorizationEncrypted 70 cleartext, err := secret.DecryptSecret(setting.SecretKey, cipherhex) 71 assert.NoError(t, err) 72 assert.Equal(t, e.HeaderAuthorization, cleartext) 73 } 74 } 75 76 // ensure that no hook_task has some remaining "access_token" 77 hookTasks := []HookTask{} 78 if err := x.Table("hook_task").Select("id, payload_content").Asc("id").Find(&hookTasks); !assert.NoError(t, err) { 79 return 80 } 81 for _, h := range hookTasks { 82 var m map[string]any 83 err := json.Unmarshal([]byte(h.PayloadContent), &m) 84 assert.NoError(t, err) 85 assert.Nil(t, m["access_token"]) 86 } 87 }