summaryrefslogtreecommitdiffstats
path: root/services/auth/oauth2_test.go
blob: c9b4ed06cc20ffb8e02a1598e1163c48fcd28e5e (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
// Copyright 2024 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package auth

import (
	"context"
	"testing"

	"code.gitea.io/gitea/models/unittest"
	user_model "code.gitea.io/gitea/models/user"
	"code.gitea.io/gitea/modules/web/middleware"
	"code.gitea.io/gitea/services/actions"

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

func TestUserIDFromToken(t *testing.T) {
	require.NoError(t, unittest.PrepareTestDatabase())

	t.Run("Actions JWT", func(t *testing.T) {
		const RunningTaskID = 47
		token, err := actions.CreateAuthorizationToken(RunningTaskID, 1, 2)
		require.NoError(t, err)

		ds := make(middleware.ContextData)

		o := OAuth2{}
		uid := o.userIDFromToken(context.Background(), token, ds)
		assert.Equal(t, int64(user_model.ActionsUserID), uid)
		assert.Equal(t, true, ds["IsActionsToken"])
		assert.Equal(t, ds["ActionsTaskID"], int64(RunningTaskID))
	})
}

func TestCheckTaskIsRunning(t *testing.T) {
	require.NoError(t, unittest.PrepareTestDatabase())
	cases := map[string]struct {
		TaskID   int64
		Expected bool
	}{
		"Running":   {TaskID: 47, Expected: true},
		"Missing":   {TaskID: 1, Expected: false},
		"Cancelled": {TaskID: 46, Expected: false},
	}

	for name := range cases {
		c := cases[name]
		t.Run(name, func(t *testing.T) {
			actual := CheckTaskIsRunning(context.Background(), c.TaskID)
			assert.Equal(t, c.Expected, actual)
		})
	}
}