summaryrefslogtreecommitdiffstats
path: root/modules/setting/oauth2_test.go
blob: 18252b24473b3e65d678c8e5bf826fc02117313d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Copyright 2024 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package setting

import (
	"os"
	"testing"

	"code.gitea.io/gitea/modules/generate"
	"code.gitea.io/gitea/modules/test"

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

func TestGetGeneralSigningSecret(t *testing.T) {
	// when there is no general signing secret, it should be generated, and keep the same value
	generalSigningSecret.Store(nil)
	s1 := GetGeneralTokenSigningSecret()
	assert.NotNil(t, s1)
	s2 := GetGeneralTokenSigningSecret()
	assert.Equal(t, s1, s2)

	// the config value should always override any pre-generated value
	cfg, _ := NewConfigProviderFromData(`
[oauth2]
JWT_SECRET = BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
`)
	defer test.MockVariableValue(&InstallLock, true)()
	loadOAuth2From(cfg)
	actual := GetGeneralTokenSigningSecret()
	expected, _ := generate.DecodeJwtSecret("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB")
	assert.Len(t, actual, 32)
	assert.EqualValues(t, expected, actual)
}

func TestGetGeneralSigningSecretSave(t *testing.T) {
	defer test.MockVariableValue(&InstallLock, true)()

	old := GetGeneralTokenSigningSecret()
	assert.Len(t, old, 32)

	tmpFile := t.TempDir() + "/app.ini"
	_ = os.WriteFile(tmpFile, nil, 0o644)
	cfg, _ := NewConfigProviderFromFile(tmpFile)
	loadOAuth2From(cfg)
	generated := GetGeneralTokenSigningSecret()
	assert.Len(t, generated, 32)
	assert.NotEqual(t, old, generated)

	generalSigningSecret.Store(nil)
	cfg, _ = NewConfigProviderFromFile(tmpFile)
	loadOAuth2From(cfg)
	again := GetGeneralTokenSigningSecret()
	assert.Equal(t, generated, again)

	iniContent, err := os.ReadFile(tmpFile)
	require.NoError(t, err)
	assert.Contains(t, string(iniContent), "JWT_SECRET = ")
}