summaryrefslogtreecommitdiff
path: root/app/jobs/create_sparkle.go
blob: 3a03b1fd5fadc6b08c659d3804c31cd153bb36ec (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package jobs

import (
	"context"
	"strings"

	v1 "github.com/authzed/authzed-go/proto/authzed/api/v1"
	"github.com/authzed/authzed-go/v1"
	"github.com/containerd/log"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/domain"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/pls"
)

type CreateSparkle struct {
	client *authzed.Client
	ctx    context.Context
}

func NewCreateSparkle(ctx context.Context, client *authzed.Client) Job[*domain.Sparkle] {
	return &CreateSparkle{
		client: client,
		ctx:    ctx,
	}
}

func (job *CreateSparkle) Run(item *domain.Sparkle) {
	response, err := job.client.WriteRelationships(job.ctx, job.requestFor(item))
	if err != nil {
		pls.LogErrorNow(job.ctx, err)
	}
	pls.LogNow(job.ctx, log.Fields{"response": response})
}

func (job *CreateSparkle) requestFor(sparkle *domain.Sparkle) *v1.WriteRelationshipsRequest {
	resource := sparkle.ToGID().ToObjectReference()

	return &v1.WriteRelationshipsRequest{
		Updates: []*v1.RelationshipUpdate{
			&v1.RelationshipUpdate{
				Operation: v1.RelationshipUpdate_OPERATION_CREATE,
				Relationship: &v1.Relationship{
					Resource: resource,
					Relation: "sparkler",
					Subject:  sparkle.Author.ToSubjectReference(),
				},
			},
			&v1.RelationshipUpdate{
				Operation: v1.RelationshipUpdate_OPERATION_CREATE,
				Relationship: &v1.Relationship{
					Resource: resource,
					Relation: "sparklee",
					Subject: &v1.SubjectReference{
						Object: &v1.ObjectReference{
							ObjectType: "user",
							ObjectId:   strings.TrimPrefix(sparkle.Sparklee, "@"),
						},
					},
				},
			},
			&v1.RelationshipUpdate{
				Operation: v1.RelationshipUpdate_OPERATION_CREATE,
				Relationship: &v1.Relationship{
					Resource: resource,
					Relation: "reader",
					Subject: &v1.SubjectReference{
						Object: &v1.ObjectReference{
							ObjectType: "user",
							ObjectId:   "*",
						},
					},
				},
			},
		},
	}
}