mirror of
https://codeberg.org/forgejo/forgejo.git
synced 2026-05-12 22:10:25 +00:00
Add support for OIDC workload identity federation.
Add ID_TOKEN_SIGNING_ALGORITHM, ID_TOKEN_SIGNING_PRIVATE_KEY_FILE, and
ID_TOKEN_EXPIRATION_TIME settings to settings.actions to allow for admin
configuration of this functionality.
Add OIDC endpoints (/.well-known/openid-configuration and /.well-known/keys)
underneath the "/api/actions" route.
Add a token generation endpoint (/_apis/pipelines/workflows/{run_id}/idtoken)
underneath the "/api/actions" route.
Depends on: https://code.forgejo.org/forgejo/runner/pulls/1232
Docs PR: https://codeberg.org/forgejo/docs/pulls/1667
Signed-off-by: Mario Minardi <mminardi@shaw.ca>
## Checklist
The [contributor guide](https://forgejo.org/docs/next/contributor/) contains information that will be helpful to first time contributors. There also are a few [conditions for merging Pull Requests in Forgejo repositories](https://codeberg.org/forgejo/governance/src/branch/main/PullRequestsAgreement.md). You are also welcome to join the [Forgejo development chatroom](https://matrix.to/#/#forgejo-development:matrix.org).
### Tests
- I added test coverage for Go changes...
- [x] in their respective `*_test.go` for unit tests.
- [x] in the `tests/integration` directory if it involves interactions with a live Forgejo server.
- I added test coverage for JavaScript changes...
- [ ] in `web_src/js/*.test.js` if it can be unit tested.
- [ ] in `tests/e2e/*.test.e2e.js` if it requires interactions with a live Forgejo server (see also the [developer guide for JavaScript testing](https://codeberg.org/forgejo/forgejo/src/branch/forgejo/tests/e2e/README.md#end-to-end-tests)).
### Documentation
- [x] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change.
- [ ] I did not document these changes and I do not expect someone else to do it.
### Release notes
- [ ] I do not want this change to show in the release notes.
- [ ] I want the title to show in the release notes with a link to this pull request.
- [ ] I want the content of the `release-notes/<pull request number>.md` to be be used for the release notes instead of the title.
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/10481
Reviewed-by: Mathieu Fenniak <mfenniak@noreply.codeberg.org>
Co-authored-by: Mario Minardi <mminardi@shaw.ca>
Co-committed-by: Mario Minardi <mminardi@shaw.ca>
669 lines
22 KiB
Go
669 lines
22 KiB
Go
// Copyright 2024 The Gitea Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package integration
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"reflect"
|
|
"strconv"
|
|
"testing"
|
|
"time"
|
|
|
|
actions_model "forgejo.org/models/actions"
|
|
auth_model "forgejo.org/models/auth"
|
|
repo_model "forgejo.org/models/repo"
|
|
"forgejo.org/models/unittest"
|
|
user_model "forgejo.org/models/user"
|
|
"forgejo.org/modules/git"
|
|
"forgejo.org/modules/json"
|
|
"forgejo.org/modules/setting"
|
|
api "forgejo.org/modules/structs"
|
|
|
|
runnerv1 "code.forgejo.org/forgejo/actions-proto/runner/v1"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestActionsJobWithNeeds(t *testing.T) {
|
|
if !setting.Database.Type.IsSQLite3() {
|
|
t.Skip()
|
|
}
|
|
testCases := []struct {
|
|
treePath string
|
|
fileContent string
|
|
outcomes map[string]*mockTaskOutcome
|
|
expectedStatuses map[string]string
|
|
}{
|
|
{
|
|
treePath: ".gitea/workflows/job-with-needs.yml",
|
|
fileContent: `name: job-with-needs
|
|
on:
|
|
push:
|
|
paths:
|
|
- '.gitea/workflows/job-with-needs.yml'
|
|
jobs:
|
|
job1:
|
|
runs-on: ubuntu-latest
|
|
steps:
|
|
- run: echo job1
|
|
job2:
|
|
runs-on: ubuntu-latest
|
|
needs: [job1]
|
|
steps:
|
|
- run: echo job2
|
|
`,
|
|
outcomes: map[string]*mockTaskOutcome{
|
|
"job1": {
|
|
result: runnerv1.Result_RESULT_SUCCESS,
|
|
},
|
|
"job2": {
|
|
result: runnerv1.Result_RESULT_SUCCESS,
|
|
},
|
|
},
|
|
expectedStatuses: map[string]string{
|
|
"job1": actions_model.StatusSuccess.String(),
|
|
"job2": actions_model.StatusSuccess.String(),
|
|
},
|
|
},
|
|
{
|
|
treePath: ".gitea/workflows/job-with-needs-fail.yml",
|
|
fileContent: `name: job-with-needs-fail
|
|
on:
|
|
push:
|
|
paths:
|
|
- '.gitea/workflows/job-with-needs-fail.yml'
|
|
jobs:
|
|
job1:
|
|
runs-on: ubuntu-latest
|
|
steps:
|
|
- run: echo job1
|
|
job2:
|
|
runs-on: ubuntu-latest
|
|
needs: [job1]
|
|
steps:
|
|
- run: echo job2
|
|
`,
|
|
outcomes: map[string]*mockTaskOutcome{
|
|
"job1": {
|
|
result: runnerv1.Result_RESULT_FAILURE,
|
|
},
|
|
},
|
|
expectedStatuses: map[string]string{
|
|
"job1": actions_model.StatusFailure.String(),
|
|
"job2": actions_model.StatusSkipped.String(),
|
|
},
|
|
},
|
|
{
|
|
treePath: ".gitea/workflows/job-with-needs-fail-if.yml",
|
|
fileContent: `name: job-with-needs-fail-if
|
|
on:
|
|
push:
|
|
paths:
|
|
- '.gitea/workflows/job-with-needs-fail-if.yml'
|
|
jobs:
|
|
job1:
|
|
runs-on: ubuntu-latest
|
|
steps:
|
|
- run: echo job1
|
|
job2:
|
|
runs-on: ubuntu-latest
|
|
if: ${{ always() }}
|
|
needs: [job1]
|
|
steps:
|
|
- run: echo job2
|
|
`,
|
|
outcomes: map[string]*mockTaskOutcome{
|
|
"job1": {
|
|
result: runnerv1.Result_RESULT_FAILURE,
|
|
},
|
|
"job2": {
|
|
result: runnerv1.Result_RESULT_SUCCESS,
|
|
},
|
|
},
|
|
expectedStatuses: map[string]string{
|
|
"job1": actions_model.StatusFailure.String(),
|
|
"job2": actions_model.StatusSuccess.String(),
|
|
},
|
|
},
|
|
}
|
|
onApplicationRun(t, func(t *testing.T, u *url.URL) {
|
|
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
|
session := loginUser(t, user2.Name)
|
|
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
|
|
|
|
apiRepo := createActionsTestRepo(t, token, "actions-jobs-with-needs", false)
|
|
runner := newMockRunner()
|
|
runner.registerAsRepoRunner(t, user2.Name, apiRepo.Name, "mock-runner", []string{"ubuntu-latest"})
|
|
|
|
for _, tc := range testCases {
|
|
t.Run(fmt.Sprintf("test %s", tc.treePath), func(t *testing.T) {
|
|
// create the workflow file
|
|
opts := getWorkflowCreateFileOptions(user2, apiRepo.DefaultBranch, fmt.Sprintf("create %s", tc.treePath), tc.fileContent)
|
|
fileResp := createWorkflowFile(t, token, user2.Name, apiRepo.Name, tc.treePath, opts)
|
|
|
|
// fetch and execute task
|
|
for i := 0; i < len(tc.outcomes); i++ {
|
|
task := runner.fetchTask(t)
|
|
jobName := getTaskJobNameByTaskID(t, token, user2.Name, apiRepo.Name, task.Id)
|
|
outcome := tc.outcomes[jobName]
|
|
assert.NotNil(t, outcome)
|
|
runner.execTask(t, task, outcome)
|
|
}
|
|
|
|
// check result
|
|
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/actions/tasks", user2.Name, apiRepo.Name)).
|
|
AddTokenAuth(token)
|
|
resp := MakeRequest(t, req, http.StatusOK)
|
|
var actionTaskRespAfter api.ActionTaskResponse
|
|
DecodeJSON(t, resp, &actionTaskRespAfter)
|
|
for _, apiTask := range actionTaskRespAfter.Entries {
|
|
if apiTask.HeadSHA != fileResp.Commit.SHA {
|
|
continue
|
|
}
|
|
status := apiTask.Status
|
|
assert.Equal(t, status, tc.expectedStatuses[apiTask.Name])
|
|
}
|
|
})
|
|
}
|
|
|
|
httpContext := NewAPITestContext(t, user2.Name, apiRepo.Name, auth_model.AccessTokenScopeWriteRepository)
|
|
doAPIDeleteRepository(httpContext)(t)
|
|
})
|
|
}
|
|
|
|
func TestActionsJobNeedsMatrix(t *testing.T) {
|
|
if !setting.Database.Type.IsSQLite3() {
|
|
t.Skip()
|
|
}
|
|
testCases := []struct {
|
|
treePath string
|
|
fileContent string
|
|
outcomes map[string]*mockTaskOutcome
|
|
expectedTaskNeeds map[string]*runnerv1.TaskNeed // jobID => TaskNeed
|
|
}{
|
|
{
|
|
treePath: ".gitea/workflows/jobs-outputs-with-matrix.yml",
|
|
fileContent: `name: jobs-outputs-with-matrix
|
|
on:
|
|
push:
|
|
paths:
|
|
- '.gitea/workflows/jobs-outputs-with-matrix.yml'
|
|
jobs:
|
|
job1:
|
|
runs-on: ubuntu-latest
|
|
outputs:
|
|
output_1: ${{ steps.gen_output.outputs.output_1 }}
|
|
output_2: ${{ steps.gen_output.outputs.output_2 }}
|
|
output_3: ${{ steps.gen_output.outputs.output_3 }}
|
|
strategy:
|
|
matrix:
|
|
version: [1, 2, 3]
|
|
steps:
|
|
- name: Generate output
|
|
id: gen_output
|
|
run: |
|
|
version="${{ matrix.version }}"
|
|
echo "output_${version}=${version}" >> "$GITHUB_OUTPUT"
|
|
job2:
|
|
runs-on: ubuntu-latest
|
|
needs: [job1]
|
|
steps:
|
|
- run: echo '${{ toJSON(needs.job1.outputs) }}'
|
|
`,
|
|
outcomes: map[string]*mockTaskOutcome{
|
|
"job1 (1)": {
|
|
result: runnerv1.Result_RESULT_SUCCESS,
|
|
outputs: map[string]string{
|
|
"output_1": "1",
|
|
"output_2": "",
|
|
"output_3": "",
|
|
},
|
|
},
|
|
"job1 (2)": {
|
|
result: runnerv1.Result_RESULT_SUCCESS,
|
|
outputs: map[string]string{
|
|
"output_1": "",
|
|
"output_2": "2",
|
|
"output_3": "",
|
|
},
|
|
},
|
|
"job1 (3)": {
|
|
result: runnerv1.Result_RESULT_SUCCESS,
|
|
outputs: map[string]string{
|
|
"output_1": "",
|
|
"output_2": "",
|
|
"output_3": "3",
|
|
},
|
|
},
|
|
},
|
|
expectedTaskNeeds: map[string]*runnerv1.TaskNeed{
|
|
"job1": {
|
|
Result: runnerv1.Result_RESULT_SUCCESS,
|
|
Outputs: map[string]string{
|
|
"output_1": "1",
|
|
"output_2": "2",
|
|
"output_3": "3",
|
|
},
|
|
},
|
|
},
|
|
},
|
|
{
|
|
treePath: ".gitea/workflows/jobs-outputs-with-matrix-failure.yml",
|
|
fileContent: `name: jobs-outputs-with-matrix-failure
|
|
on:
|
|
push:
|
|
paths:
|
|
- '.gitea/workflows/jobs-outputs-with-matrix-failure.yml'
|
|
jobs:
|
|
job1:
|
|
runs-on: ubuntu-latest
|
|
outputs:
|
|
output_1: ${{ steps.gen_output.outputs.output_1 }}
|
|
output_2: ${{ steps.gen_output.outputs.output_2 }}
|
|
output_3: ${{ steps.gen_output.outputs.output_3 }}
|
|
strategy:
|
|
matrix:
|
|
version: [1, 2, 3]
|
|
steps:
|
|
- name: Generate output
|
|
id: gen_output
|
|
run: |
|
|
version="${{ matrix.version }}"
|
|
echo "output_${version}=${version}" >> "$GITHUB_OUTPUT"
|
|
job2:
|
|
runs-on: ubuntu-latest
|
|
if: ${{ always() }}
|
|
needs: [job1]
|
|
steps:
|
|
- run: echo '${{ toJSON(needs.job1.outputs) }}'
|
|
`,
|
|
outcomes: map[string]*mockTaskOutcome{
|
|
"job1 (1)": {
|
|
result: runnerv1.Result_RESULT_SUCCESS,
|
|
outputs: map[string]string{
|
|
"output_1": "1",
|
|
"output_2": "",
|
|
"output_3": "",
|
|
},
|
|
},
|
|
"job1 (2)": {
|
|
result: runnerv1.Result_RESULT_FAILURE,
|
|
outputs: map[string]string{
|
|
"output_1": "",
|
|
"output_2": "",
|
|
"output_3": "",
|
|
},
|
|
},
|
|
"job1 (3)": {
|
|
result: runnerv1.Result_RESULT_SUCCESS,
|
|
outputs: map[string]string{
|
|
"output_1": "",
|
|
"output_2": "",
|
|
"output_3": "3",
|
|
},
|
|
},
|
|
},
|
|
expectedTaskNeeds: map[string]*runnerv1.TaskNeed{
|
|
"job1": {
|
|
Result: runnerv1.Result_RESULT_FAILURE,
|
|
Outputs: map[string]string{
|
|
"output_1": "1",
|
|
"output_2": "",
|
|
"output_3": "3",
|
|
},
|
|
},
|
|
},
|
|
},
|
|
}
|
|
onApplicationRun(t, func(t *testing.T, u *url.URL) {
|
|
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
|
session := loginUser(t, user2.Name)
|
|
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
|
|
|
|
apiRepo := createActionsTestRepo(t, token, "actions-jobs-outputs-with-matrix", false)
|
|
runner := newMockRunner()
|
|
runner.registerAsRepoRunner(t, user2.Name, apiRepo.Name, "mock-runner", []string{"ubuntu-latest"})
|
|
|
|
for _, tc := range testCases {
|
|
t.Run(fmt.Sprintf("test %s", tc.treePath), func(t *testing.T) {
|
|
opts := getWorkflowCreateFileOptions(user2, apiRepo.DefaultBranch, fmt.Sprintf("create %s", tc.treePath), tc.fileContent)
|
|
createWorkflowFile(t, token, user2.Name, apiRepo.Name, tc.treePath, opts)
|
|
|
|
for i := 0; i < len(tc.outcomes); i++ {
|
|
task := runner.fetchTask(t)
|
|
jobName := getTaskJobNameByTaskID(t, token, user2.Name, apiRepo.Name, task.Id)
|
|
outcome := tc.outcomes[jobName]
|
|
assert.NotNil(t, outcome)
|
|
runner.execTask(t, task, outcome)
|
|
}
|
|
|
|
task := runner.fetchTask(t)
|
|
actualTaskNeeds := task.Needs
|
|
assert.Len(t, actualTaskNeeds, len(tc.expectedTaskNeeds))
|
|
for jobID, tn := range tc.expectedTaskNeeds {
|
|
actualNeed := actualTaskNeeds[jobID]
|
|
assert.Equal(t, tn.Result, actualNeed.Result)
|
|
assert.Len(t, actualNeed.Outputs, len(tn.Outputs))
|
|
for outputKey, outputValue := range tn.Outputs {
|
|
assert.Equal(t, outputValue, actualNeed.Outputs[outputKey])
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
httpContext := NewAPITestContext(t, user2.Name, apiRepo.Name, auth_model.AccessTokenScopeWriteRepository)
|
|
doAPIDeleteRepository(httpContext)(t)
|
|
})
|
|
}
|
|
|
|
func TestActionsGiteaContext(t *testing.T) {
|
|
if !setting.Database.Type.IsSQLite3() {
|
|
t.Skip()
|
|
}
|
|
|
|
testCases := []struct {
|
|
name string
|
|
treePath string
|
|
fileContent string
|
|
enableOpenIDConnect bool
|
|
}{
|
|
{
|
|
name: "openid_connect_disabled",
|
|
treePath: ".gitea/workflows/pull.yml",
|
|
fileContent: `name: Pull Request
|
|
on: pull_request
|
|
jobs:
|
|
wf1-job:
|
|
runs-on: ubuntu-latest
|
|
steps:
|
|
- run: echo 'test the pull'
|
|
`,
|
|
enableOpenIDConnect: false,
|
|
},
|
|
{
|
|
name: "openid_connect_enabled",
|
|
treePath: ".gitea/workflows/pull-enabled.yml",
|
|
fileContent: `name: Pull Request
|
|
on: pull_request
|
|
jobs:
|
|
wf1-job:
|
|
enable-openid-connect: true
|
|
runs-on: ubuntu-latest
|
|
steps:
|
|
- run: echo 'test the pull'
|
|
`,
|
|
enableOpenIDConnect: true,
|
|
},
|
|
}
|
|
|
|
onApplicationRun(t, func(t *testing.T, u *url.URL) {
|
|
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
|
user2Session := loginUser(t, user2.Name)
|
|
user2Token := getTokenForLoggedInUser(t, user2Session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
|
|
|
|
apiBaseRepo := createActionsTestRepo(t, user2Token, "actions-gitea-context", false)
|
|
baseRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiBaseRepo.ID})
|
|
user2APICtx := NewAPITestContext(t, baseRepo.OwnerName, baseRepo.Name, auth_model.AccessTokenScopeWriteRepository)
|
|
|
|
runner := newMockRunner()
|
|
runner.registerAsRepoRunner(t, baseRepo.OwnerName, baseRepo.Name, "mock-runner", []string{"ubuntu-latest"})
|
|
|
|
for _, tc := range testCases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
opts := getWorkflowCreateFileOptions(user2, baseRepo.DefaultBranch, fmt.Sprintf("create %s", tc.treePath), tc.fileContent)
|
|
createWorkflowFile(t, user2Token, baseRepo.OwnerName, baseRepo.Name, tc.treePath, opts)
|
|
// user2 creates a pull request
|
|
doAPICreateFile(user2APICtx, "user2-patch.txt", &api.CreateFileOptions{
|
|
FileOptions: api.FileOptions{
|
|
NewBranchName: tc.name,
|
|
Message: "create user2-patch.txt",
|
|
Author: api.Identity{
|
|
Name: user2.Name,
|
|
Email: user2.Email,
|
|
},
|
|
Committer: api.Identity{
|
|
Name: user2.Name,
|
|
Email: user2.Email,
|
|
},
|
|
Dates: api.CommitDateOptions{
|
|
Author: time.Now(),
|
|
Committer: time.Now(),
|
|
},
|
|
},
|
|
ContentBase64: base64.StdEncoding.EncodeToString([]byte("user2-fix")),
|
|
})(t)
|
|
apiPull, err := doAPICreatePullRequest(user2APICtx, baseRepo.OwnerName, baseRepo.Name, baseRepo.DefaultBranch, tc.name)(t)
|
|
require.NoError(t, err)
|
|
task := runner.fetchTask(t)
|
|
gtCtx := task.Context.GetFields()
|
|
actionTask := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionTask{ID: task.Id})
|
|
actionRunJob := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{ID: actionTask.JobID})
|
|
actionRun := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: actionRunJob.RunID})
|
|
require.NoError(t, actionRun.LoadAttributes(t.Context()))
|
|
|
|
assert.Equal(t, user2.Name, gtCtx["actor"].GetStringValue())
|
|
assert.Equal(t, setting.AppURL+"api/v1", gtCtx["api_url"].GetStringValue())
|
|
assert.Equal(t, apiPull.Base.Ref, gtCtx["base_ref"].GetStringValue())
|
|
runEvent := map[string]any{}
|
|
require.NoError(t, json.Unmarshal([]byte(actionRun.EventPayload), &runEvent))
|
|
assert.True(t, reflect.DeepEqual(gtCtx["event"].GetStructValue().AsMap(), runEvent))
|
|
assert.Equal(t, actionRun.TriggerEvent, gtCtx["event_name"].GetStringValue())
|
|
assert.Equal(t, apiPull.Head.Ref, gtCtx["head_ref"].GetStringValue())
|
|
assert.Equal(t, actionRunJob.JobID, gtCtx["job"].GetStringValue())
|
|
assert.Equal(t, actionRun.Ref, gtCtx["ref"].GetStringValue())
|
|
assert.Equal(t, (git.RefName(actionRun.Ref)).ShortName(), gtCtx["ref_name"].GetStringValue())
|
|
assert.False(t, gtCtx["ref_protected"].GetBoolValue())
|
|
assert.Equal(t, (git.RefName(actionRun.Ref)).RefType(), gtCtx["ref_type"].GetStringValue())
|
|
assert.Equal(t, actionRun.Repo.OwnerName+"/"+actionRun.Repo.Name, gtCtx["repository"].GetStringValue())
|
|
assert.Equal(t, actionRun.Repo.OwnerName, gtCtx["repository_owner"].GetStringValue())
|
|
assert.Equal(t, actionRun.Repo.HTMLURL(), gtCtx["repositoryUrl"].GetStringValue())
|
|
assert.Equal(t, fmt.Sprint(actionRunJob.RunID), gtCtx["run_id"].GetStringValue())
|
|
assert.Equal(t, fmt.Sprint(actionRun.Index), gtCtx["run_number"].GetStringValue())
|
|
assert.Equal(t, fmt.Sprint(actionRunJob.Attempt), gtCtx["run_attempt"].GetStringValue())
|
|
assert.Equal(t, "Actions", gtCtx["secret_source"].GetStringValue())
|
|
assert.Equal(t, setting.AppURL, gtCtx["server_url"].GetStringValue())
|
|
assert.Equal(t, actionRun.CommitSHA, gtCtx["sha"].GetStringValue())
|
|
assert.Equal(t, actionRun.WorkflowID, gtCtx["workflow"].GetStringValue())
|
|
assert.Contains(t, gtCtx["workflow_ref"].GetStringValue(), fmt.Sprintf("user2/actions-gitea-context/%s@refs/pull", tc.treePath))
|
|
assert.Equal(t, setting.Actions.DefaultActionsURL.URL(), gtCtx["gitea_default_actions_url"].GetStringValue())
|
|
assert.Equal(t, setting.AppVer, gtCtx["forgejo_server_version"].GetStringValue())
|
|
token := gtCtx["token"].GetStringValue()
|
|
assert.Equal(t, actionTask.TokenLastEight, token[len(token)-8:])
|
|
if tc.enableOpenIDConnect {
|
|
assert.NotEmpty(t, gtCtx["forgejo_actions_id_token_request_token"].GetStringValue())
|
|
assert.Equal(t,
|
|
fmt.Sprintf("%sapi/actions/_apis/pipelines/workflows/%d/idtoken?placeholder=true",
|
|
setting.AppURL, actionRunJob.RunID), gtCtx["forgejo_actions_id_token_request_url"].GetStringValue(),
|
|
)
|
|
} else {
|
|
assert.Empty(t, gtCtx["forgejo_actions_id_token_request_token"].GetStringValue())
|
|
assert.Empty(t, gtCtx["forgejo_actions_id_token_request_url"].GetStringValue())
|
|
}
|
|
})
|
|
}
|
|
|
|
doAPIDeleteRepository(user2APICtx)(t)
|
|
})
|
|
}
|
|
|
|
func TestActionsRunsOnInputsWorkflowDispatch(t *testing.T) {
|
|
if !setting.Database.Type.IsSQLite3() {
|
|
t.Skip()
|
|
}
|
|
|
|
onApplicationRun(t, func(t *testing.T, u *url.URL) {
|
|
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
|
session := loginUser(t, user2.Name)
|
|
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
|
|
|
|
testRepository := createActionsTestRepo(t, token, "actions-runs-on-inputs-workflow-dispatch", false)
|
|
|
|
ubuntuRunner := newMockRunner()
|
|
ubuntuRunner.registerAsRepoRunner(t, user2.Name, testRepository.Name, "ubuntu-runner", []string{"ubuntu"})
|
|
|
|
windowsRunner := newMockRunner()
|
|
windowsRunner.registerAsRepoRunner(t, user2.Name, testRepository.Name, "windows-runner", []string{"windows"})
|
|
|
|
workflowPath := ".gitea/workflows/pull.yaml"
|
|
workflow := `name: Test runs-on with inputs
|
|
on:
|
|
workflow_dispatch:
|
|
inputs:
|
|
image:
|
|
required: true
|
|
type: string
|
|
|
|
jobs:
|
|
test:
|
|
runs-on: ${{ inputs.image }}
|
|
steps:
|
|
- run: echo "Running on ${{ inputs.image }}"
|
|
`
|
|
|
|
options := getWorkflowCreateFileOptions(user2, testRepository.DefaultBranch, fmt.Sprintf("create %s", workflowPath), workflow)
|
|
createWorkflowFile(t, token, user2.Name, testRepository.Name, workflowPath, options)
|
|
|
|
url := fmt.Sprintf("/%s/%s/actions/manual", user2.Name, testRepository.Name)
|
|
request := NewRequestWithValues(t, "POST", url, map[string]string{
|
|
"inputs[image]": "windows",
|
|
"ref": testRepository.DefaultBranch,
|
|
"workflow": "pull.yaml",
|
|
"actor": strconv.FormatInt(user2.ID, 10),
|
|
})
|
|
session.MakeRequest(t, request, http.StatusSeeOther)
|
|
|
|
assert.Nil(t, ubuntuRunner.maybeFetchTask(t))
|
|
|
|
task := windowsRunner.fetchTask(t)
|
|
actionTask := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionTask{ID: task.Id})
|
|
actionRunJob := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{ID: actionTask.JobID})
|
|
run := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: actionRunJob.RunID})
|
|
|
|
assert.Equal(t, "Test runs-on with inputs", run.Title)
|
|
})
|
|
}
|
|
|
|
func TestActionsRunsOnVars(t *testing.T) {
|
|
if !setting.Database.Type.IsSQLite3() {
|
|
t.Skip()
|
|
}
|
|
|
|
onApplicationRun(t, func(t *testing.T, u *url.URL) {
|
|
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
|
session := loginUser(t, user2.Name)
|
|
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
|
|
|
|
testRepository := createActionsTestRepo(t, token, "actions-runs-on-vars", false)
|
|
|
|
ubuntuRunner := newMockRunner()
|
|
ubuntuRunner.registerAsRepoRunner(t, user2.Name, testRepository.Name, "ubuntu-runner", []string{"ubuntu"})
|
|
|
|
windowsRunner := newMockRunner()
|
|
windowsRunner.registerAsRepoRunner(t, user2.Name, testRepository.Name, "windows-runner", []string{"windows"})
|
|
|
|
workflowPath := ".gitea/workflows/pull.yaml"
|
|
workflow := `name: Test runs-on with vars
|
|
on:
|
|
workflow_dispatch:
|
|
|
|
jobs:
|
|
test:
|
|
runs-on: ${{ vars.runner }}
|
|
steps:
|
|
- run: echo "Running on ${{ vars.runner }}"
|
|
`
|
|
|
|
options := getWorkflowCreateFileOptions(user2, testRepository.DefaultBranch, fmt.Sprintf("create %s", workflowPath), workflow)
|
|
createWorkflowFile(t, token, user2.Name, testRepository.Name, workflowPath, options)
|
|
|
|
varCreationURL := fmt.Sprintf("/%s/%s/settings/actions/variables/new", user2.Name, testRepository.Name)
|
|
varCreationRequest := NewRequestWithValues(t, "POST", varCreationURL, map[string]string{
|
|
"name": "runner",
|
|
"data": "ubuntu",
|
|
})
|
|
session.MakeRequest(t, varCreationRequest, http.StatusOK)
|
|
|
|
dispatchURL := fmt.Sprintf("/%s/%s/actions/manual", user2.Name, testRepository.Name)
|
|
dispatchRequest := NewRequestWithValues(t, "POST", dispatchURL, map[string]string{
|
|
"ref": testRepository.DefaultBranch,
|
|
"workflow": "pull.yaml",
|
|
"actor": strconv.FormatInt(user2.ID, 10),
|
|
})
|
|
session.MakeRequest(t, dispatchRequest, http.StatusSeeOther)
|
|
|
|
assert.Nil(t, windowsRunner.maybeFetchTask(t))
|
|
|
|
task := ubuntuRunner.fetchTask(t)
|
|
actionTask := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionTask{ID: task.Id})
|
|
actionRunJob := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRunJob{ID: actionTask.JobID})
|
|
run := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: actionRunJob.RunID})
|
|
|
|
assert.Equal(t, "Test runs-on with vars", run.Title)
|
|
})
|
|
}
|
|
|
|
func createActionsTestRepo(t *testing.T, authToken, repoName string, isPrivate bool) *api.Repository {
|
|
req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos", &api.CreateRepoOption{
|
|
Name: repoName,
|
|
Private: isPrivate,
|
|
Readme: "Default",
|
|
AutoInit: true,
|
|
DefaultBranch: "main",
|
|
}).AddTokenAuth(authToken)
|
|
resp := MakeRequest(t, req, http.StatusCreated)
|
|
var apiRepo api.Repository
|
|
DecodeJSON(t, resp, &apiRepo)
|
|
return &apiRepo
|
|
}
|
|
|
|
func getWorkflowCreateFileOptions(u *user_model.User, branch, msg, content string) *api.CreateFileOptions {
|
|
return &api.CreateFileOptions{
|
|
FileOptions: api.FileOptions{
|
|
BranchName: branch,
|
|
Message: msg,
|
|
Author: api.Identity{
|
|
Name: u.Name,
|
|
Email: u.Email,
|
|
},
|
|
Committer: api.Identity{
|
|
Name: u.Name,
|
|
Email: u.Email,
|
|
},
|
|
Dates: api.CommitDateOptions{
|
|
Author: time.Now(),
|
|
Committer: time.Now(),
|
|
},
|
|
},
|
|
ContentBase64: base64.StdEncoding.EncodeToString([]byte(content)),
|
|
}
|
|
}
|
|
|
|
func createWorkflowFile(t *testing.T, authToken, ownerName, repoName, treePath string, opts *api.CreateFileOptions) *api.FileResponse {
|
|
req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", ownerName, repoName, treePath), opts).
|
|
AddTokenAuth(authToken)
|
|
resp := MakeRequest(t, req, http.StatusCreated)
|
|
var fileResponse api.FileResponse
|
|
DecodeJSON(t, resp, &fileResponse)
|
|
return &fileResponse
|
|
}
|
|
|
|
// getTaskJobNameByTaskID get the job name of the task by task ID
|
|
// there is currently not an API for querying a task by ID so we have to list all the tasks
|
|
func getTaskJobNameByTaskID(t *testing.T, authToken, ownerName, repoName string, taskID int64) string {
|
|
// FIXME: we may need to query several pages
|
|
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/actions/tasks", ownerName, repoName)).
|
|
AddTokenAuth(authToken)
|
|
resp := MakeRequest(t, req, http.StatusOK)
|
|
var taskRespBefore api.ActionTaskResponse
|
|
DecodeJSON(t, resp, &taskRespBefore)
|
|
for _, apiTask := range taskRespBefore.Entries {
|
|
if apiTask.ID == taskID {
|
|
return apiTask.Name
|
|
}
|
|
}
|
|
return ""
|
|
}
|