Skip to content

Commit c1fe8e3

Browse files
committed
chore: Add script to generate JSON input for policy evaluation
1 parent f119821 commit c1fe8e3

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

coderd/rbac/scripts/gen_input.go

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"log"
6+
"os"
7+
8+
"github.com/google/uuid"
9+
"golang.org/x/xerrors"
10+
11+
"github.com/coder/coder/v2/coderd/rbac"
12+
"github.com/coder/coder/v2/coderd/rbac/policy"
13+
)
14+
15+
type SubjectJSON struct {
16+
ID string `json:"id"`
17+
Roles []rbac.Role `json:"roles"`
18+
Groups []string `json:"groups"`
19+
Scope rbac.Scope `json:"scope"`
20+
}
21+
type OutputData struct {
22+
Action policy.Action `json:"action"`
23+
Object rbac.Object `json:"object"`
24+
Subject *SubjectJSON `json:"subject"`
25+
}
26+
27+
func newSubjectJSON(s rbac.Subject) (*SubjectJSON, error) {
28+
roles, err := s.Roles.Expand()
29+
if err != nil {
30+
return nil, xerrors.Errorf("failed to expand subject roles: %w", err)
31+
}
32+
scopes, err := s.Scope.Expand()
33+
if err != nil {
34+
return nil, xerrors.Errorf("failed to expand subject scopes: %w", err)
35+
}
36+
return &SubjectJSON{
37+
ID: s.ID,
38+
Roles: roles,
39+
Groups: s.Groups,
40+
Scope: scopes,
41+
}, nil
42+
}
43+
44+
// TODO: support arguments for subject, action and object
45+
func main() {
46+
// Template Admin user
47+
subject := rbac.Subject{
48+
FriendlyName: "Test Name",
49+
Email: "test@coder.com",
50+
Type: "user",
51+
ID: uuid.New().String(),
52+
Roles: rbac.RoleIdentifiers{
53+
rbac.RoleTemplateAdmin(),
54+
},
55+
Scope: rbac.ScopeAll,
56+
}
57+
58+
subjectJSON, err := newSubjectJSON(subject)
59+
if err != nil {
60+
log.Fatalf("Failed to convert to subject to JSON: %v", err)
61+
}
62+
63+
// Delete action
64+
action := policy.ActionDelete
65+
66+
// Prebuilt Workspace object
67+
object := rbac.Object{
68+
ID: uuid.New().String(),
69+
Owner: "c42fdf75-3097-471c-8c33-fb52454d81c0",
70+
OrgID: "663f8241-23e0-41c4-a621-cec3a347318e",
71+
Type: "prebuilt_workspace",
72+
}
73+
74+
// Output file path
75+
outputPath := "input.json"
76+
77+
output := OutputData{
78+
Action: action,
79+
Object: object,
80+
Subject: subjectJSON,
81+
}
82+
83+
outputBytes, err := json.MarshalIndent(output, "", " ")
84+
if err != nil {
85+
log.Fatalf("Failed to marshal output to json: %v", err)
86+
}
87+
88+
if err := os.WriteFile(outputPath, outputBytes, 0o600); err != nil {
89+
log.Fatalf("Failed to generate input file: %v", err)
90+
}
91+
92+
log.Printf("Input JSON written to %s\n", outputPath)
93+
}

0 commit comments

Comments
 (0)